1use std::collections::{BTreeMap, HashSet};
2use std::rc::Rc;
3use std::sync::Arc;
4use std::time::Instant;
5
6use crate::chunk::{Chunk, ChunkRef, Constant};
7use crate::runtime_limits::RuntimeLimits;
8use crate::value::{
9 ModuleFunctionRegistry, VmAsyncBuiltinFn, VmBuiltinFn, VmEnv, VmError, VmTaskHandle, VmValue,
10};
11use crate::BuiltinId;
12
13use super::debug::DebugHook;
14use super::modules::LoadedModule;
15use super::VmBuiltinMetadata;
16
17pub(crate) struct ScopeSpan(u64);
19
20impl ScopeSpan {
21 pub(crate) fn new(kind: crate::tracing::SpanKind, name: String) -> Self {
22 Self(crate::tracing::span_start(kind, name))
23 }
24}
25
26impl Drop for ScopeSpan {
27 fn drop(&mut self) {
28 crate::tracing::span_end(self.0);
29 }
30}
31
32#[derive(Clone)]
33pub(crate) struct LocalSlot {
34 pub(crate) value: VmValue,
35 pub(crate) initialized: bool,
36 pub(crate) synced: bool,
37}
38
39#[derive(Clone)]
40pub(crate) struct InterruptHandler {
41 pub(crate) handle: i64,
42 pub(crate) signals: Vec<String>,
43 pub(crate) once: bool,
44 pub(crate) graceful_timeout_ms: Option<u64>,
45 pub(crate) handler: VmValue,
46}
47
48pub(crate) struct CallFrame {
50 pub(crate) chunk: ChunkRef,
51 pub(crate) ip: usize,
52 pub(crate) stack_base: usize,
53 pub(crate) saved_env: VmEnv,
54 pub(crate) initial_env: Option<VmEnv>,
62 pub(crate) initial_local_slots: Option<Vec<LocalSlot>>,
63 pub(crate) saved_iterator_depth: usize,
65 pub(crate) fn_name: String,
67 pub(crate) argc: usize,
69 pub(crate) saved_source_dir: Option<std::path::PathBuf>,
72 pub(crate) module_functions: Option<ModuleFunctionRegistry>,
74 pub(crate) module_state: Option<crate::value::ModuleState>,
80 pub(crate) local_slots: Vec<LocalSlot>,
82 pub(crate) local_scope_base: usize,
84 pub(crate) local_scope_depth: usize,
86}
87
88pub(crate) struct ExceptionHandler {
90 pub(crate) catch_ip: usize,
91 pub(crate) stack_depth: usize,
92 pub(crate) frame_depth: usize,
93 pub(crate) env_scope_depth: usize,
94 pub(crate) error_type: Option<Rc<str>>,
96}
97
98pub(crate) enum IterState {
100 Vec {
101 items: Rc<Vec<VmValue>>,
102 idx: usize,
103 },
104 Dict {
105 entries: Rc<BTreeMap<String, VmValue>>,
106 keys: Vec<String>,
107 idx: usize,
108 },
109 Channel {
110 receiver: std::sync::Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<VmValue>>>,
111 closed: std::sync::Arc<std::sync::atomic::AtomicBool>,
112 },
113 Generator {
114 gen: std::rc::Rc<crate::value::VmGenerator>,
115 },
116 Stream {
117 stream: std::rc::Rc<crate::value::VmStream>,
118 },
119 Range {
123 next: i64,
124 end: i64,
125 inclusive: bool,
126 done: bool,
127 },
128 VmIter {
129 handle: std::rc::Rc<std::cell::RefCell<crate::vm::iter::VmIter>>,
130 },
131}
132
133#[derive(Clone)]
134pub(crate) enum VmBuiltinDispatch {
135 Sync(VmBuiltinFn),
136 Async(VmAsyncBuiltinFn),
137}
138
139#[derive(Clone)]
140pub(crate) struct VmBuiltinEntry {
141 pub(crate) name: Rc<str>,
142 pub(crate) dispatch: VmBuiltinDispatch,
143}
144
145pub struct Vm {
147 pub(crate) stack: Vec<VmValue>,
148 pub(crate) env: VmEnv,
149 pub(crate) output: String,
150 pub(crate) builtins: Rc<BTreeMap<String, VmBuiltinFn>>,
151 pub(crate) async_builtins: Rc<BTreeMap<String, VmAsyncBuiltinFn>>,
152 pub(crate) builtin_metadata: Rc<BTreeMap<String, VmBuiltinMetadata>>,
153 pub(crate) builtins_by_id: Rc<BTreeMap<BuiltinId, VmBuiltinEntry>>,
156 pub(crate) builtin_id_collisions: Rc<HashSet<BuiltinId>>,
159 pub(crate) iterators: Vec<IterState>,
161 pub(crate) frames: Vec<CallFrame>,
163 pub(crate) exception_handlers: Vec<ExceptionHandler>,
165 pub(crate) spawned_tasks: BTreeMap<String, VmTaskHandle>,
167 pub(crate) sync_runtime: Arc<crate::synchronization::VmSyncRuntime>,
169 pub(crate) shared_state_runtime: Rc<crate::shared_state::VmSharedStateRuntime>,
171 pub(crate) held_sync_guards: Vec<crate::synchronization::VmSyncHeldGuard>,
173 pub(crate) task_counter: u64,
175 pub(crate) runtime_context_counter: u64,
177 pub(crate) runtime_context: crate::runtime_context::RuntimeContext,
179 pub(crate) deadlines: Vec<(Instant, usize)>,
181 pub(crate) breakpoints: BTreeMap<String, std::collections::BTreeSet<usize>>,
186 pub(crate) function_breakpoints: std::collections::BTreeSet<String>,
192 pub(crate) pending_function_bp: Option<String>,
197 pub(crate) step_mode: bool,
199 pub(crate) step_frame_depth: usize,
201 pub(crate) stopped: bool,
203 pub(crate) last_line: usize,
205 pub(crate) source_dir: Option<std::path::PathBuf>,
207 pub(crate) imported_paths: Vec<std::path::PathBuf>,
209 pub(crate) module_cache: Rc<BTreeMap<std::path::PathBuf, LoadedModule>>,
211 pub(crate) source_cache: Rc<BTreeMap<std::path::PathBuf, String>>,
213 pub(crate) source_file: Option<String>,
215 pub(crate) source_text: Option<String>,
217 pub(crate) bridge: Option<Rc<crate::bridge::HostBridge>>,
219 pub(crate) denied_builtins: Rc<HashSet<String>>,
221 pub(crate) cancel_token: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
223 pub(crate) interrupt_signal_token: Option<std::sync::Arc<std::sync::Mutex<Option<String>>>>,
224 pub(crate) cancel_grace_instructions_remaining: Option<usize>,
229 pub(crate) interrupt_handlers: Vec<InterruptHandler>,
231 pub(crate) next_interrupt_handle: i64,
232 pub(crate) pending_interrupt_signal: Option<String>,
233 pub(crate) interrupted: bool,
234 pub(crate) dispatching_interrupt: bool,
235 pub(crate) interrupt_handler_deadline: Option<Instant>,
236 pub(crate) error_stack_trace: Vec<(String, usize, usize, Option<String>)>,
238 pub(crate) yield_sender: Option<tokio::sync::mpsc::Sender<Result<VmValue, VmError>>>,
241 pub(crate) project_root: Option<std::path::PathBuf>,
244 pub(crate) globals: Rc<BTreeMap<String, VmValue>>,
247 pub(crate) debug_hook: Option<Box<DebugHook>>,
249 pub(crate) runtime_limits: RuntimeLimits,
251}
252
253#[derive(Clone)]
261pub struct VmBaseline {
262 builtins: Rc<BTreeMap<String, VmBuiltinFn>>,
263 async_builtins: Rc<BTreeMap<String, VmAsyncBuiltinFn>>,
264 builtin_metadata: Rc<BTreeMap<String, VmBuiltinMetadata>>,
265 builtins_by_id: Rc<BTreeMap<BuiltinId, VmBuiltinEntry>>,
266 builtin_id_collisions: Rc<HashSet<BuiltinId>>,
267 source_dir: Option<std::path::PathBuf>,
268 source_file: Option<String>,
269 source_text: Option<String>,
270 project_root: Option<std::path::PathBuf>,
271 globals: Rc<BTreeMap<String, VmValue>>,
272 denied_builtins: Rc<HashSet<String>>,
273 runtime_limits: RuntimeLimits,
274}
275
276impl VmBaseline {
277 pub fn from_vm(vm: &Vm) -> Self {
278 Self {
279 builtins: Rc::clone(&vm.builtins),
280 async_builtins: Rc::clone(&vm.async_builtins),
281 builtin_metadata: Rc::clone(&vm.builtin_metadata),
282 builtins_by_id: Rc::clone(&vm.builtins_by_id),
283 builtin_id_collisions: Rc::clone(&vm.builtin_id_collisions),
284 source_dir: vm.source_dir.clone(),
285 source_file: vm.source_file.clone(),
286 source_text: vm.source_text.clone(),
287 project_root: vm.project_root.clone(),
288 globals: Rc::clone(&vm.globals),
289 denied_builtins: Rc::clone(&vm.denied_builtins),
290 runtime_limits: vm.runtime_limits,
291 }
292 }
293
294 pub fn instantiate(&self) -> Vm {
295 let mut source_cache = BTreeMap::new();
296 if let (Some(file), Some(text)) = (&self.source_file, &self.source_text) {
297 source_cache.insert(std::path::PathBuf::from(file), text.clone());
298 }
299 if let Some(dir) = &self.source_dir {
300 crate::stdlib::set_thread_source_dir(dir);
301 }
302
303 let mut vm = Vm {
304 stack: Vec::with_capacity(256),
305 env: VmEnv::new(),
306 output: String::new(),
307 builtins: Rc::clone(&self.builtins),
308 async_builtins: Rc::clone(&self.async_builtins),
309 builtin_metadata: Rc::clone(&self.builtin_metadata),
310 builtins_by_id: Rc::clone(&self.builtins_by_id),
311 builtin_id_collisions: Rc::clone(&self.builtin_id_collisions),
312 iterators: Vec::new(),
313 frames: Vec::new(),
314 exception_handlers: Vec::new(),
315 spawned_tasks: BTreeMap::new(),
316 sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
317 shared_state_runtime: Rc::new(crate::shared_state::VmSharedStateRuntime::new()),
318 held_sync_guards: Vec::new(),
319 task_counter: 0,
320 runtime_context_counter: 0,
321 runtime_context: crate::runtime_context::RuntimeContext::root(),
322 deadlines: Vec::new(),
323 breakpoints: BTreeMap::new(),
324 function_breakpoints: std::collections::BTreeSet::new(),
325 pending_function_bp: None,
326 step_mode: false,
327 step_frame_depth: 0,
328 stopped: false,
329 last_line: 0,
330 source_dir: self.source_dir.clone(),
331 imported_paths: Vec::new(),
332 module_cache: Rc::new(BTreeMap::new()),
333 source_cache: Rc::new(source_cache),
334 source_file: self.source_file.clone(),
335 source_text: self.source_text.clone(),
336 bridge: None,
337 denied_builtins: Rc::clone(&self.denied_builtins),
338 cancel_token: None,
339 interrupt_signal_token: None,
340 cancel_grace_instructions_remaining: None,
341 interrupt_handlers: Vec::new(),
342 next_interrupt_handle: 1,
343 pending_interrupt_signal: None,
344 interrupted: false,
345 dispatching_interrupt: false,
346 interrupt_handler_deadline: None,
347 error_stack_trace: Vec::new(),
348 yield_sender: None,
349 project_root: self.project_root.clone(),
350 globals: Rc::clone(&self.globals),
351 debug_hook: None,
352 runtime_limits: self.runtime_limits,
353 };
354
355 crate::stdlib::rebind_execution_state_builtins(&mut vm);
356 vm
357 }
358}
359
360impl Vm {
361 pub(crate) fn fresh_local_slots(chunk: &Chunk) -> Vec<LocalSlot> {
362 chunk
363 .local_slots
364 .iter()
365 .map(|_| LocalSlot {
366 value: VmValue::Nil,
367 initialized: false,
368 synced: false,
369 })
370 .collect()
371 }
372
373 pub(crate) fn bind_param_slots(
374 slots: &mut [LocalSlot],
375 func: &crate::chunk::CompiledFunction,
376 args: &[VmValue],
377 synced: bool,
378 ) {
379 Self::bind_param_slots_args(slots, func, &super::CallArgs::Slice(args), synced);
380 }
381
382 pub(crate) fn bind_param_slots_args(
383 slots: &mut [LocalSlot],
384 func: &crate::chunk::CompiledFunction,
385 args: &super::CallArgs<'_>,
386 synced: bool,
387 ) {
388 let param_count = func.params.len();
389 for (i, _param) in func.params.iter().enumerate() {
390 if i >= slots.len() {
391 break;
392 }
393 if func.has_rest_param && i == param_count - 1 {
394 let rest_args = args.to_vec_from(i);
395 slots[i].value = VmValue::List(Rc::new(rest_args));
396 slots[i].initialized = true;
397 slots[i].synced = synced;
398 } else if let Some(arg) = args.get(i) {
399 slots[i].value = arg.clone();
400 slots[i].initialized = true;
401 slots[i].synced = synced;
402 }
403 }
404 }
405
406 pub(crate) fn visible_variables(&self) -> BTreeMap<String, VmValue> {
407 let mut vars = self.env.all_variables();
408 let Some(frame) = self.frames.last() else {
409 return vars;
410 };
411 for (slot, info) in frame.local_slots.iter().zip(frame.chunk.local_slots.iter()) {
412 if slot.initialized && info.scope_depth <= frame.local_scope_depth {
413 vars.insert(info.name.clone(), slot.value.clone());
414 }
415 }
416 vars
417 }
418
419 pub(crate) fn sync_current_frame_locals_to_env(&mut self) {
420 let frames = &mut self.frames;
421 let env = &mut self.env;
422 let Some(frame) = frames.last_mut() else {
423 return;
424 };
425 let local_scope_base = frame.local_scope_base;
426 let local_scope_depth = frame.local_scope_depth;
427 for (slot, info) in frame
428 .local_slots
429 .iter_mut()
430 .zip(frame.chunk.local_slots.iter())
431 {
432 if slot.initialized && !slot.synced && info.scope_depth <= local_scope_depth {
433 slot.synced = true;
434 let scope_idx = local_scope_base + info.scope_depth;
435 while env.scopes.len() <= scope_idx {
436 env.push_scope();
437 }
438 Rc::make_mut(&mut env.scopes[scope_idx].vars)
439 .insert(info.name.clone(), (slot.value.clone(), info.mutable));
440 }
441 }
442 }
443
444 pub(crate) fn closure_call_env_for_current_frame(
445 &self,
446 closure: &crate::value::VmClosure,
447 ) -> VmEnv {
448 if closure.module_state.is_some() {
449 return closure.env.clone();
450 }
451 let call_env = Self::closure_call_env(&self.env, closure);
452 if !closure.func.chunk.references_outer_names {
457 return call_env;
458 }
459 let mut call_env = call_env;
460 let Some(frame) = self.frames.last() else {
461 return call_env;
462 };
463 for (slot, info) in frame
464 .local_slots
465 .iter()
466 .zip(frame.chunk.local_slots.iter())
467 .filter(|(slot, info)| slot.initialized && info.scope_depth <= frame.local_scope_depth)
468 {
469 if matches!(slot.value, VmValue::Closure(_)) && !call_env.contains(&info.name) {
470 let _ = call_env.define(&info.name, slot.value.clone(), info.mutable);
471 }
472 }
473 call_env
474 }
475
476 pub(crate) fn active_local_slot_value(&self, name: &str) -> Option<VmValue> {
477 let frame = self.frames.last()?;
478 let idx = self.active_local_slot_index(name)?;
479 frame.local_slots.get(idx).map(|slot| slot.value.clone())
480 }
481
482 pub(crate) fn active_local_slot_index(&self, name: &str) -> Option<usize> {
487 let frame = self.frames.last()?;
488 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
489 if info.name == name && info.scope_depth <= frame.local_scope_depth {
490 if let Some(slot) = frame.local_slots.get(idx) {
491 if slot.initialized {
492 return Some(idx);
493 }
494 }
495 }
496 }
497 None
498 }
499
500 pub(crate) fn assign_active_local_slot(
501 &mut self,
502 name: &str,
503 value: VmValue,
504 debug: bool,
505 ) -> Result<bool, VmError> {
506 let Some(frame) = self.frames.last_mut() else {
507 return Ok(false);
508 };
509 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
510 if info.name == name && info.scope_depth <= frame.local_scope_depth {
511 if !debug && !info.mutable {
512 return Err(VmError::ImmutableAssignment(name.to_string()));
513 }
514 if let Some(slot) = frame.local_slots.get_mut(idx) {
515 slot.value = value;
516 slot.initialized = true;
517 slot.synced = false;
518 return Ok(true);
519 }
520 }
521 }
522 Ok(false)
523 }
524
525 pub fn new() -> Self {
526 Self {
527 stack: Vec::with_capacity(256),
528 env: VmEnv::new(),
529 output: String::new(),
530 builtins: Rc::new(BTreeMap::new()),
531 async_builtins: Rc::new(BTreeMap::new()),
532 builtin_metadata: Rc::new(BTreeMap::new()),
533 builtins_by_id: Rc::new(BTreeMap::new()),
534 builtin_id_collisions: Rc::new(HashSet::new()),
535 iterators: Vec::new(),
536 frames: Vec::new(),
537 exception_handlers: Vec::new(),
538 spawned_tasks: BTreeMap::new(),
539 sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
540 shared_state_runtime: Rc::new(crate::shared_state::VmSharedStateRuntime::new()),
541 held_sync_guards: Vec::new(),
542 task_counter: 0,
543 runtime_context_counter: 0,
544 runtime_context: crate::runtime_context::RuntimeContext::root(),
545 deadlines: Vec::new(),
546 breakpoints: BTreeMap::new(),
547 function_breakpoints: std::collections::BTreeSet::new(),
548 pending_function_bp: None,
549 step_mode: false,
550 step_frame_depth: 0,
551 stopped: false,
552 last_line: 0,
553 source_dir: None,
554 imported_paths: Vec::new(),
555 module_cache: Rc::new(BTreeMap::new()),
556 source_cache: Rc::new(BTreeMap::new()),
557 source_file: None,
558 source_text: None,
559 bridge: None,
560 denied_builtins: Rc::new(HashSet::new()),
561 cancel_token: None,
562 interrupt_signal_token: None,
563 cancel_grace_instructions_remaining: None,
564 interrupt_handlers: Vec::new(),
565 next_interrupt_handle: 1,
566 pending_interrupt_signal: None,
567 interrupted: false,
568 dispatching_interrupt: false,
569 interrupt_handler_deadline: None,
570 error_stack_trace: Vec::new(),
571 yield_sender: None,
572 project_root: None,
573 globals: Rc::new(BTreeMap::new()),
574 debug_hook: None,
575 runtime_limits: RuntimeLimits::default(),
576 }
577 }
578
579 pub fn baseline(&self) -> VmBaseline {
580 VmBaseline::from_vm(self)
581 }
582
583 pub fn runtime_limits(&self) -> RuntimeLimits {
585 self.runtime_limits
586 }
587
588 pub fn runtime_limit_report(&self) -> crate::RuntimeLimitsReport {
590 self.runtime_limits.report()
591 }
592
593 #[inline]
607 pub(crate) fn debugger_attached(&self) -> bool {
608 self.debug_hook.is_some()
609 || !self.breakpoints.is_empty()
610 || !self.function_breakpoints.is_empty()
611 }
612
613 pub fn set_bridge(&mut self, bridge: Rc<crate::bridge::HostBridge>) {
615 self.bridge = Some(bridge);
616 }
617
618 pub fn set_denied_builtins(&mut self, denied: HashSet<String>) {
621 self.denied_builtins = Rc::new(denied);
622 }
623
624 pub fn set_source_info(&mut self, file: &str, text: &str) {
626 self.source_file = Some(file.to_string());
627 self.source_text = Some(text.to_string());
628 Rc::make_mut(&mut self.source_cache)
629 .insert(std::path::PathBuf::from(file), text.to_string());
630 }
631
632 pub fn start(&mut self, chunk: &Chunk) {
634 let debugger = self.debugger_attached();
641 let initial_env = if debugger {
642 Some(self.env.clone())
643 } else {
644 None
645 };
646 let initial_local_slots = if debugger {
647 Some(Self::fresh_local_slots(chunk))
648 } else {
649 None
650 };
651 self.frames.push(CallFrame {
652 chunk: Rc::new(chunk.clone()),
653 ip: 0,
654 stack_base: self.stack.len(),
655 saved_env: self.env.clone(),
656 initial_env,
657 initial_local_slots,
658 saved_iterator_depth: self.iterators.len(),
659 fn_name: String::new(),
660 argc: 0,
661 saved_source_dir: None,
662 module_functions: None,
663 module_state: None,
664 local_slots: Self::fresh_local_slots(chunk),
665 local_scope_base: self.env.scope_depth().saturating_sub(1),
666 local_scope_depth: 0,
667 });
668 }
669
670 pub(crate) fn child_vm(&self) -> Vm {
673 Vm {
674 stack: Vec::with_capacity(64),
675 env: self.env.clone(),
676 output: String::new(),
677 builtins: Rc::clone(&self.builtins),
678 async_builtins: Rc::clone(&self.async_builtins),
679 builtin_metadata: Rc::clone(&self.builtin_metadata),
680 builtins_by_id: Rc::clone(&self.builtins_by_id),
681 builtin_id_collisions: Rc::clone(&self.builtin_id_collisions),
682 iterators: Vec::new(),
683 frames: Vec::new(),
684 exception_handlers: Vec::new(),
685 spawned_tasks: BTreeMap::new(),
686 sync_runtime: self.sync_runtime.clone(),
687 shared_state_runtime: self.shared_state_runtime.clone(),
688 held_sync_guards: Vec::new(),
689 task_counter: 0,
690 runtime_context_counter: self.runtime_context_counter,
691 runtime_context: self.runtime_context.clone(),
692 deadlines: self.deadlines.clone(),
693 breakpoints: BTreeMap::new(),
694 function_breakpoints: std::collections::BTreeSet::new(),
695 pending_function_bp: None,
696 step_mode: false,
697 step_frame_depth: 0,
698 stopped: false,
699 last_line: 0,
700 source_dir: self.source_dir.clone(),
701 imported_paths: Vec::new(),
702 module_cache: Rc::clone(&self.module_cache),
703 source_cache: Rc::clone(&self.source_cache),
704 source_file: self.source_file.clone(),
705 source_text: self.source_text.clone(),
706 bridge: self.bridge.clone(),
707 denied_builtins: Rc::clone(&self.denied_builtins),
708 cancel_token: self.cancel_token.clone(),
709 interrupt_signal_token: self.interrupt_signal_token.clone(),
710 cancel_grace_instructions_remaining: None,
711 interrupt_handlers: Vec::new(),
712 next_interrupt_handle: 1,
713 pending_interrupt_signal: None,
714 interrupted: self.interrupted,
715 dispatching_interrupt: false,
716 interrupt_handler_deadline: None,
717 error_stack_trace: Vec::new(),
718 yield_sender: None,
719 project_root: self.project_root.clone(),
720 globals: Rc::clone(&self.globals),
721 debug_hook: None,
722 runtime_limits: self.runtime_limits,
723 }
724 }
725
726 pub(crate) fn child_vm_for_host(&self) -> Vm {
729 self.child_vm()
730 }
731
732 pub(crate) fn cancel_spawned_tasks(&mut self) {
736 for (_, task) in std::mem::take(&mut self.spawned_tasks) {
737 task.cancel_token
738 .store(true, std::sync::atomic::Ordering::SeqCst);
739 task.handle.abort();
740 }
741 }
742
743 pub fn set_source_dir(&mut self, dir: &std::path::Path) {
746 let dir = crate::stdlib::process::normalize_context_path(dir);
747 self.source_dir = Some(dir.clone());
748 crate::stdlib::set_thread_source_dir(&dir);
749 if self.project_root.is_none() {
751 self.project_root = crate::stdlib::process::find_project_root(&dir);
752 }
753 }
754
755 pub fn set_project_root(&mut self, root: &std::path::Path) {
758 self.project_root = Some(root.to_path_buf());
759 }
760
761 pub fn project_root(&self) -> Option<&std::path::Path> {
763 self.project_root.as_deref().or(self.source_dir.as_deref())
764 }
765
766 pub fn builtin_names(&self) -> Vec<String> {
768 let mut names: Vec<String> = self.builtins.keys().cloned().collect();
769 names.extend(self.async_builtins.keys().cloned());
770 names
771 }
772
773 pub fn builtin_metadata(&self) -> Vec<VmBuiltinMetadata> {
775 self.builtin_metadata.values().cloned().collect()
776 }
777
778 pub fn builtin_metadata_for(&self, name: &str) -> Option<&VmBuiltinMetadata> {
780 self.builtin_metadata.get(name)
781 }
782
783 pub fn set_global(&mut self, name: &str, value: VmValue) {
786 Rc::make_mut(&mut self.globals).insert(name.to_string(), value);
787 }
788
789 pub fn global(&self, name: &str) -> Option<&VmValue> {
795 self.globals.get(name)
796 }
797
798 pub fn set_harness(&mut self, harness: crate::harness::Harness) {
804 self.set_global("harness", harness.into_vm_value());
805 }
806
807 pub fn output(&self) -> &str {
809 &self.output
810 }
811
812 pub fn take_output(&mut self) -> String {
816 std::mem::take(&mut self.output)
817 }
818
819 pub fn append_output(&mut self, text: &str) {
823 self.output.push_str(text);
824 }
825
826 pub(crate) fn pop(&mut self) -> Result<VmValue, VmError> {
827 self.stack.pop().ok_or(VmError::StackUnderflow)
828 }
829
830 pub(crate) fn peek(&self) -> Result<&VmValue, VmError> {
831 self.stack.last().ok_or(VmError::StackUnderflow)
832 }
833
834 pub(crate) fn const_str(c: &Constant) -> Result<&str, VmError> {
835 match c {
836 Constant::String(s) => Ok(s.as_str()),
837 _ => Err(VmError::TypeError("expected string constant".into())),
838 }
839 }
840
841 pub(crate) fn release_sync_guards_for_current_scope(&mut self) {
842 let depth = self.env.scope_depth();
843 self.held_sync_guards
844 .retain(|guard| guard.env_scope_depth < depth);
845 }
846
847 pub(crate) fn release_sync_guards_after_unwind(
848 &mut self,
849 frame_depth: usize,
850 env_scope_depth: usize,
851 ) {
852 self.held_sync_guards.retain(|guard| {
853 guard.frame_depth <= frame_depth && guard.env_scope_depth <= env_scope_depth
854 });
855 }
856
857 pub(crate) fn release_sync_guards_for_frame(&mut self, frame_depth: usize) {
858 self.held_sync_guards
859 .retain(|guard| guard.frame_depth != frame_depth);
860 }
861}
862
863impl Drop for Vm {
864 fn drop(&mut self) {
865 self.cancel_spawned_tasks();
866 }
867}
868
869impl Default for Vm {
870 fn default() -> Self {
871 Self::new()
872 }
873}
874
875#[cfg(test)]
876mod tests {
877 use std::rc::Rc;
878
879 use super::*;
880
881 fn baseline_with_stdlib(source: &str) -> VmBaseline {
882 let mut vm = Vm::new();
883 crate::register_vm_stdlib(&mut vm);
884 vm.set_source_info("baseline_test.harn", source);
885 vm.set_global("stable_global", VmValue::String(Rc::from("baseline")));
886 vm.baseline()
887 }
888
889 #[test]
890 fn vm_baseline_instantiates_clean_mutable_execution_state() {
891 let baseline = baseline_with_stdlib("pipeline main() { __io_println(stable_global) }");
892
893 let mut dirty = baseline.instantiate();
894 dirty.stack.push(VmValue::Int(42));
895 dirty.output.push_str("dirty");
896 dirty.task_counter = 9;
897 dirty.runtime_context_counter = 7;
898 dirty
899 .error_stack_trace
900 .push(("main".to_string(), 1, 1, None));
901
902 let clean = baseline.instantiate();
903 assert!(clean.stack.is_empty());
904 assert!(clean.output.is_empty());
905 assert!(clean.frames.is_empty());
906 assert!(clean.exception_handlers.is_empty());
907 assert!(clean.spawned_tasks.is_empty());
908 assert!(clean.held_sync_guards.is_empty());
909 assert_eq!(clean.task_counter, 0);
910 assert_eq!(clean.runtime_context_counter, 0);
911 assert!(clean.deadlines.is_empty());
912 assert!(clean.cancel_token.is_none());
913 assert!(clean.interrupt_handlers.is_empty());
914 assert!(clean.error_stack_trace.is_empty());
915 assert!(clean.bridge.is_none());
916 assert!(clean
917 .globals
918 .get("stable_global")
919 .is_some_and(|value| value.display() == "baseline"));
920 }
921
922 #[test]
923 fn vm_reports_effective_runtime_limits() {
924 let vm = Vm::new();
925
926 assert_eq!(vm.runtime_limits(), RuntimeLimits::default());
927 assert_eq!(
928 vm.runtime_limit_report().entries.len(),
929 crate::RUNTIME_LIMIT_DESCRIPTIONS.len()
930 );
931 assert_eq!(vm.child_vm().runtime_limits(), vm.runtime_limits());
932 assert_eq!(
933 vm.baseline().instantiate().runtime_limits(),
934 vm.runtime_limits()
935 );
936 }
937
938 #[tokio::test(flavor = "current_thread")]
939 async fn vm_baseline_rebinds_shared_state_builtins_per_instance() {
940 let local = tokio::task::LocalSet::new();
941 local
942 .run_until(async {
943 let source = r#"
944pipeline main() {
945 let cell = shared_cell({scope: "task_group", key: "turn", initial: 0})
946 __io_println(shared_get(cell))
947 shared_set(cell, shared_get(cell) + 1)
948}"#;
949 let chunk = crate::compile_source(source).expect("compile");
950 let baseline = baseline_with_stdlib(source);
951
952 let mut first = baseline.instantiate();
953 first.execute(&chunk).await.expect("first execute");
954 assert_eq!(first.output(), "0\n");
955
956 let mut second = baseline.instantiate();
957 second.execute(&chunk).await.expect("second execute");
958 assert_eq!(
959 second.output(),
960 "0\n",
961 "shared state created by the first VM must not leak into the next baseline instance"
962 );
963 })
964 .await;
965 }
966}