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::value::{
8 ModuleFunctionRegistry, VmAsyncBuiltinFn, VmBuiltinFn, VmEnv, VmError, VmTaskHandle, VmValue,
9};
10use crate::BuiltinId;
11
12use super::debug::DebugHook;
13use super::modules::LoadedModule;
14
15pub(crate) struct ScopeSpan(u64);
17
18impl ScopeSpan {
19 pub(crate) fn new(kind: crate::tracing::SpanKind, name: String) -> Self {
20 Self(crate::tracing::span_start(kind, name))
21 }
22}
23
24impl Drop for ScopeSpan {
25 fn drop(&mut self) {
26 crate::tracing::span_end(self.0);
27 }
28}
29
30#[derive(Clone)]
31pub(crate) struct LocalSlot {
32 pub(crate) value: VmValue,
33 pub(crate) initialized: bool,
34 pub(crate) synced: bool,
35}
36
37pub(crate) struct CallFrame {
39 pub(crate) chunk: ChunkRef,
40 pub(crate) ip: usize,
41 pub(crate) stack_base: usize,
42 pub(crate) saved_env: VmEnv,
43 pub(crate) initial_env: Option<VmEnv>,
51 pub(crate) initial_local_slots: Option<Vec<LocalSlot>>,
52 pub(crate) saved_iterator_depth: usize,
54 pub(crate) fn_name: String,
56 pub(crate) argc: usize,
58 pub(crate) saved_source_dir: Option<std::path::PathBuf>,
61 pub(crate) module_functions: Option<ModuleFunctionRegistry>,
63 pub(crate) module_state: Option<crate::value::ModuleState>,
69 pub(crate) local_slots: Vec<LocalSlot>,
71 pub(crate) local_scope_base: usize,
73 pub(crate) local_scope_depth: usize,
75}
76
77pub(crate) struct ExceptionHandler {
79 pub(crate) catch_ip: usize,
80 pub(crate) stack_depth: usize,
81 pub(crate) frame_depth: usize,
82 pub(crate) env_scope_depth: usize,
83 pub(crate) error_type: String,
85}
86
87pub(crate) enum IterState {
89 Vec {
90 items: Rc<Vec<VmValue>>,
91 idx: usize,
92 },
93 Dict {
94 entries: Rc<BTreeMap<String, VmValue>>,
95 keys: Vec<String>,
96 idx: usize,
97 },
98 Channel {
99 receiver: std::sync::Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<VmValue>>>,
100 closed: std::sync::Arc<std::sync::atomic::AtomicBool>,
101 },
102 Generator {
103 gen: crate::value::VmGenerator,
104 },
105 Stream {
106 stream: crate::value::VmStream,
107 },
108 Range {
112 next: i64,
113 stop: i64,
114 },
115 VmIter {
116 handle: std::rc::Rc<std::cell::RefCell<crate::vm::iter::VmIter>>,
117 },
118}
119
120#[derive(Clone)]
121pub(crate) enum VmBuiltinDispatch {
122 Sync(VmBuiltinFn),
123 Async(VmAsyncBuiltinFn),
124}
125
126#[derive(Clone)]
127pub(crate) struct VmBuiltinEntry {
128 pub(crate) name: Rc<str>,
129 pub(crate) dispatch: VmBuiltinDispatch,
130}
131
132pub struct Vm {
134 pub(crate) stack: Vec<VmValue>,
135 pub(crate) env: VmEnv,
136 pub(crate) output: String,
137 pub(crate) builtins: BTreeMap<String, VmBuiltinFn>,
138 pub(crate) async_builtins: BTreeMap<String, VmAsyncBuiltinFn>,
139 pub(crate) builtins_by_id: BTreeMap<BuiltinId, VmBuiltinEntry>,
142 pub(crate) builtin_id_collisions: HashSet<BuiltinId>,
145 pub(crate) iterators: Vec<IterState>,
147 pub(crate) frames: Vec<CallFrame>,
149 pub(crate) exception_handlers: Vec<ExceptionHandler>,
151 pub(crate) spawned_tasks: BTreeMap<String, VmTaskHandle>,
153 pub(crate) sync_runtime: Arc<crate::synchronization::VmSyncRuntime>,
155 pub(crate) shared_state_runtime: Rc<crate::shared_state::VmSharedStateRuntime>,
157 pub(crate) held_sync_guards: Vec<crate::synchronization::VmSyncHeldGuard>,
159 pub(crate) task_counter: u64,
161 pub(crate) runtime_context_counter: u64,
163 pub(crate) runtime_context: crate::runtime_context::RuntimeContext,
165 pub(crate) deadlines: Vec<(Instant, usize)>,
167 pub(crate) breakpoints: BTreeMap<String, std::collections::BTreeSet<usize>>,
172 pub(crate) function_breakpoints: std::collections::BTreeSet<String>,
178 pub(crate) pending_function_bp: Option<String>,
183 pub(crate) step_mode: bool,
185 pub(crate) step_frame_depth: usize,
187 pub(crate) stopped: bool,
189 pub(crate) last_line: usize,
191 pub(crate) source_dir: Option<std::path::PathBuf>,
193 pub(crate) imported_paths: Vec<std::path::PathBuf>,
195 pub(crate) module_cache: BTreeMap<std::path::PathBuf, LoadedModule>,
197 pub(crate) source_file: Option<String>,
199 pub(crate) source_text: Option<String>,
201 pub(crate) bridge: Option<Rc<crate::bridge::HostBridge>>,
203 pub(crate) denied_builtins: HashSet<String>,
205 pub(crate) cancel_token: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
207 pub(crate) cancel_grace_instructions_remaining: Option<usize>,
212 pub(crate) error_stack_trace: Vec<(String, usize, usize, Option<String>)>,
214 pub(crate) yield_sender: Option<tokio::sync::mpsc::Sender<Result<VmValue, VmError>>>,
217 pub(crate) project_root: Option<std::path::PathBuf>,
220 pub(crate) globals: BTreeMap<String, VmValue>,
223 pub(crate) debug_hook: Option<Box<DebugHook>>,
225}
226
227impl Vm {
228 pub(crate) fn fresh_local_slots(chunk: &Chunk) -> Vec<LocalSlot> {
229 chunk
230 .local_slots
231 .iter()
232 .map(|_| LocalSlot {
233 value: VmValue::Nil,
234 initialized: false,
235 synced: false,
236 })
237 .collect()
238 }
239
240 pub(crate) fn bind_param_slots(
241 slots: &mut [LocalSlot],
242 func: &crate::chunk::CompiledFunction,
243 args: &[VmValue],
244 synced: bool,
245 ) {
246 let default_start = func.default_start.unwrap_or(func.params.len());
247 let param_count = func.params.len();
248 for (i, _param) in func.params.iter().enumerate() {
249 if i >= slots.len() {
250 break;
251 }
252 if func.has_rest_param && i == param_count - 1 {
253 let rest_args = if i < args.len() {
254 args[i..].to_vec()
255 } else {
256 Vec::new()
257 };
258 slots[i].value = VmValue::List(Rc::new(rest_args));
259 slots[i].initialized = true;
260 slots[i].synced = synced;
261 } else if i < args.len() {
262 slots[i].value = args[i].clone();
263 slots[i].initialized = true;
264 slots[i].synced = synced;
265 } else if i < default_start {
266 slots[i].value = VmValue::Nil;
267 slots[i].initialized = true;
268 slots[i].synced = synced;
269 }
270 }
271 }
272
273 pub(crate) fn visible_variables(&self) -> BTreeMap<String, VmValue> {
274 let mut vars = self.env.all_variables();
275 let Some(frame) = self.frames.last() else {
276 return vars;
277 };
278 for (slot, info) in frame.local_slots.iter().zip(frame.chunk.local_slots.iter()) {
279 if slot.initialized && info.scope_depth <= frame.local_scope_depth {
280 vars.insert(info.name.clone(), slot.value.clone());
281 }
282 }
283 vars
284 }
285
286 pub(crate) fn sync_current_frame_locals_to_env(&mut self) {
287 let Some(frame) = self.frames.last_mut() else {
288 return;
289 };
290 let local_scope_base = frame.local_scope_base;
291 let local_scope_depth = frame.local_scope_depth;
292 let entries = frame
293 .local_slots
294 .iter_mut()
295 .zip(frame.chunk.local_slots.iter())
296 .filter_map(|(slot, info)| {
297 if slot.initialized && !slot.synced && info.scope_depth <= local_scope_depth {
298 slot.synced = true;
299 Some((
300 local_scope_base + info.scope_depth,
301 info.name.clone(),
302 slot.value.clone(),
303 info.mutable,
304 ))
305 } else {
306 None
307 }
308 })
309 .collect::<Vec<_>>();
310 for (scope_idx, name, value, mutable) in entries {
311 while self.env.scopes.len() <= scope_idx {
312 self.env.push_scope();
313 }
314 self.env.scopes[scope_idx]
315 .vars
316 .insert(name, (value, mutable));
317 }
318 }
319
320 pub(crate) fn closure_call_env_for_current_frame(
321 &self,
322 closure: &crate::value::VmClosure,
323 ) -> VmEnv {
324 if closure.module_state.is_some() {
325 return closure.env.clone();
326 }
327 let mut call_env = Self::closure_call_env(&self.env, closure);
328 let Some(frame) = self.frames.last() else {
329 return call_env;
330 };
331 for (slot, info) in frame
332 .local_slots
333 .iter()
334 .zip(frame.chunk.local_slots.iter())
335 .filter(|(slot, info)| slot.initialized && info.scope_depth <= frame.local_scope_depth)
336 {
337 if matches!(slot.value, VmValue::Closure(_)) && call_env.get(&info.name).is_none() {
338 let _ = call_env.define(&info.name, slot.value.clone(), info.mutable);
339 }
340 }
341 call_env
342 }
343
344 pub(crate) fn active_local_slot_value(&self, name: &str) -> Option<VmValue> {
345 let frame = self.frames.last()?;
346 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
347 if info.name == name && info.scope_depth <= frame.local_scope_depth {
348 let slot = frame.local_slots.get(idx)?;
349 if slot.initialized {
350 return Some(slot.value.clone());
351 }
352 }
353 }
354 None
355 }
356
357 pub(crate) fn assign_active_local_slot(
358 &mut self,
359 name: &str,
360 value: VmValue,
361 debug: bool,
362 ) -> Result<bool, VmError> {
363 let Some(frame) = self.frames.last_mut() else {
364 return Ok(false);
365 };
366 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
367 if info.name == name && info.scope_depth <= frame.local_scope_depth {
368 if !debug && !info.mutable {
369 return Err(VmError::ImmutableAssignment(name.to_string()));
370 }
371 if let Some(slot) = frame.local_slots.get_mut(idx) {
372 slot.value = value;
373 slot.initialized = true;
374 slot.synced = false;
375 return Ok(true);
376 }
377 }
378 }
379 Ok(false)
380 }
381
382 pub fn new() -> Self {
383 Self {
384 stack: Vec::with_capacity(256),
385 env: VmEnv::new(),
386 output: String::new(),
387 builtins: BTreeMap::new(),
388 async_builtins: BTreeMap::new(),
389 builtins_by_id: BTreeMap::new(),
390 builtin_id_collisions: HashSet::new(),
391 iterators: Vec::new(),
392 frames: Vec::new(),
393 exception_handlers: Vec::new(),
394 spawned_tasks: BTreeMap::new(),
395 sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
396 shared_state_runtime: Rc::new(crate::shared_state::VmSharedStateRuntime::new()),
397 held_sync_guards: Vec::new(),
398 task_counter: 0,
399 runtime_context_counter: 0,
400 runtime_context: crate::runtime_context::RuntimeContext::root(),
401 deadlines: Vec::new(),
402 breakpoints: BTreeMap::new(),
403 function_breakpoints: std::collections::BTreeSet::new(),
404 pending_function_bp: None,
405 step_mode: false,
406 step_frame_depth: 0,
407 stopped: false,
408 last_line: 0,
409 source_dir: None,
410 imported_paths: Vec::new(),
411 module_cache: BTreeMap::new(),
412 source_file: None,
413 source_text: None,
414 bridge: None,
415 denied_builtins: HashSet::new(),
416 cancel_token: None,
417 cancel_grace_instructions_remaining: None,
418 error_stack_trace: Vec::new(),
419 yield_sender: None,
420 project_root: None,
421 globals: BTreeMap::new(),
422 debug_hook: None,
423 }
424 }
425
426 pub fn set_bridge(&mut self, bridge: Rc<crate::bridge::HostBridge>) {
428 self.bridge = Some(bridge);
429 }
430
431 pub fn set_denied_builtins(&mut self, denied: HashSet<String>) {
434 self.denied_builtins = denied;
435 }
436
437 pub fn set_source_info(&mut self, file: &str, text: &str) {
439 self.source_file = Some(file.to_string());
440 self.source_text = Some(text.to_string());
441 }
442
443 pub fn start(&mut self, chunk: &Chunk) {
445 let initial_env = self.env.clone();
446 self.frames.push(CallFrame {
447 chunk: Rc::new(chunk.clone()),
448 ip: 0,
449 stack_base: self.stack.len(),
450 saved_env: self.env.clone(),
451 initial_env: Some(initial_env),
456 initial_local_slots: Some(Self::fresh_local_slots(chunk)),
457 saved_iterator_depth: self.iterators.len(),
458 fn_name: String::new(),
459 argc: 0,
460 saved_source_dir: None,
461 module_functions: None,
462 module_state: None,
463 local_slots: Self::fresh_local_slots(chunk),
464 local_scope_base: self.env.scope_depth().saturating_sub(1),
465 local_scope_depth: 0,
466 });
467 }
468
469 pub(crate) fn child_vm(&self) -> Vm {
472 Vm {
473 stack: Vec::with_capacity(64),
474 env: self.env.clone(),
475 output: String::new(),
476 builtins: self.builtins.clone(),
477 async_builtins: self.async_builtins.clone(),
478 builtins_by_id: self.builtins_by_id.clone(),
479 builtin_id_collisions: self.builtin_id_collisions.clone(),
480 iterators: Vec::new(),
481 frames: Vec::new(),
482 exception_handlers: Vec::new(),
483 spawned_tasks: BTreeMap::new(),
484 sync_runtime: self.sync_runtime.clone(),
485 shared_state_runtime: self.shared_state_runtime.clone(),
486 held_sync_guards: Vec::new(),
487 task_counter: 0,
488 runtime_context_counter: self.runtime_context_counter,
489 runtime_context: self.runtime_context.clone(),
490 deadlines: self.deadlines.clone(),
491 breakpoints: BTreeMap::new(),
492 function_breakpoints: std::collections::BTreeSet::new(),
493 pending_function_bp: None,
494 step_mode: false,
495 step_frame_depth: 0,
496 stopped: false,
497 last_line: 0,
498 source_dir: self.source_dir.clone(),
499 imported_paths: Vec::new(),
500 module_cache: self.module_cache.clone(),
501 source_file: self.source_file.clone(),
502 source_text: self.source_text.clone(),
503 bridge: self.bridge.clone(),
504 denied_builtins: self.denied_builtins.clone(),
505 cancel_token: self.cancel_token.clone(),
506 cancel_grace_instructions_remaining: None,
507 error_stack_trace: Vec::new(),
508 yield_sender: None,
509 project_root: self.project_root.clone(),
510 globals: self.globals.clone(),
511 debug_hook: None,
512 }
513 }
514
515 pub(crate) fn child_vm_for_host(&self) -> Vm {
518 self.child_vm()
519 }
520
521 pub(crate) fn cancel_spawned_tasks(&mut self) {
525 for (_, task) in std::mem::take(&mut self.spawned_tasks) {
526 task.cancel_token
527 .store(true, std::sync::atomic::Ordering::SeqCst);
528 task.handle.abort();
529 }
530 }
531
532 pub fn set_source_dir(&mut self, dir: &std::path::Path) {
535 let dir = crate::stdlib::process::normalize_context_path(dir);
536 self.source_dir = Some(dir.clone());
537 crate::stdlib::set_thread_source_dir(&dir);
538 if self.project_root.is_none() {
540 self.project_root = crate::stdlib::process::find_project_root(&dir);
541 }
542 }
543
544 pub fn set_project_root(&mut self, root: &std::path::Path) {
547 self.project_root = Some(root.to_path_buf());
548 }
549
550 pub fn project_root(&self) -> Option<&std::path::Path> {
552 self.project_root.as_deref().or(self.source_dir.as_deref())
553 }
554
555 pub fn builtin_names(&self) -> Vec<String> {
557 let mut names: Vec<String> = self.builtins.keys().cloned().collect();
558 names.extend(self.async_builtins.keys().cloned());
559 names
560 }
561
562 pub fn set_global(&mut self, name: &str, value: VmValue) {
565 self.globals.insert(name.to_string(), value);
566 }
567
568 pub fn output(&self) -> &str {
570 &self.output
571 }
572
573 pub(crate) fn pop(&mut self) -> Result<VmValue, VmError> {
574 self.stack.pop().ok_or(VmError::StackUnderflow)
575 }
576
577 pub(crate) fn peek(&self) -> Result<&VmValue, VmError> {
578 self.stack.last().ok_or(VmError::StackUnderflow)
579 }
580
581 pub(crate) fn const_string(c: &Constant) -> Result<String, VmError> {
582 match c {
583 Constant::String(s) => Ok(s.clone()),
584 _ => Err(VmError::TypeError("expected string constant".into())),
585 }
586 }
587
588 pub(crate) fn release_sync_guards_for_current_scope(&mut self) {
589 let depth = self.env.scope_depth();
590 self.held_sync_guards
591 .retain(|guard| guard.env_scope_depth < depth);
592 }
593
594 pub(crate) fn release_sync_guards_after_unwind(
595 &mut self,
596 frame_depth: usize,
597 env_scope_depth: usize,
598 ) {
599 self.held_sync_guards.retain(|guard| {
600 guard.frame_depth <= frame_depth && guard.env_scope_depth <= env_scope_depth
601 });
602 }
603
604 pub(crate) fn release_sync_guards_for_frame(&mut self, frame_depth: usize) {
605 self.held_sync_guards
606 .retain(|guard| guard.frame_depth != frame_depth);
607 }
608}
609
610impl Drop for Vm {
611 fn drop(&mut self) {
612 self.cancel_spawned_tasks();
613 }
614}
615
616impl Default for Vm {
617 fn default() -> Self {
618 Self::new()
619 }
620}