Skip to main content

sema_vm/
chunk.rs

1use sema_core::{Span, Spur, Value};
2
3/// A compiled code object (bytecode + metadata).
4#[derive(Debug, Clone)]
5pub struct Chunk {
6    pub code: Vec<u8>,
7    pub consts: Vec<Value>,
8    pub spans: Vec<(u32, Span)>, // sparse PC → source span mapping (sorted by PC)
9    pub max_stack: u16,
10    pub n_locals: u16,
11    pub exception_table: Vec<ExceptionEntry>,
12}
13
14impl Chunk {
15    pub fn new() -> Self {
16        Chunk {
17            code: Vec::new(),
18            consts: Vec::new(),
19            spans: Vec::new(),
20            max_stack: 0,
21            n_locals: 0,
22            exception_table: Vec::new(),
23        }
24    }
25}
26
27impl Default for Chunk {
28    fn default() -> Self {
29        Self::new()
30    }
31}
32
33#[derive(Debug, Clone)]
34pub struct ExceptionEntry {
35    pub try_start: u32,
36    pub try_end: u32,
37    pub handler_pc: u32,
38    pub stack_depth: u16,
39    pub catch_slot: u16,
40}
41
42/// A compiled function (template for closures).
43#[derive(Debug, Clone)]
44pub struct Function {
45    pub name: Option<Spur>,
46    pub chunk: Chunk,
47    pub upvalue_descs: Vec<UpvalueDesc>,
48    pub arity: u16,
49    pub has_rest: bool,
50    pub local_names: Vec<(u16, Spur)>,
51}
52
53/// Describes how an upvalue is captured relative to the immediately enclosing function.
54#[derive(Debug, Clone, Copy)]
55pub enum UpvalueDesc {
56    /// Capture from the parent function's local slot.
57    ParentLocal(u16),
58    /// Capture from the parent function's upvalue slot.
59    ParentUpvalue(u16),
60}