Skip to main content

byteflow/bytecode/
chunk.rs

1use super::instruction::Instruction;
2use super::value::Value;
3
4/// On-disk magic for the `.bf` module format (see design notes §32).
5/// Chosen so a corrupted/truncated file is rejected in the first 4 bytes
6/// rather than partway through decoding.
7pub const MAGIC: [u8; 4] = *b"BFV0";
8
9/// Current ABI version. Bump on any breaking change to instruction
10/// encoding, constant representation, or function-table layout.
11///
12/// v2: [`Value::Message`] wire tag `5`.
13/// v3: `Message.reply_cap`; [`Value::Cap`] wire tag `6` (FlowCap).
14/// v4: [`Value::Str`] tag `7`, [`Value::Bytes`] tag `8`.
15/// v5: CapId is 128-bit; `Message.payload` is a nested [`Value`].
16/// v6: [`Value::List`] wire tag `9`. Modules without a list still encode
17/// as v5 so an older reader keeps accepting them. A list constant is
18/// written only as v6; v5 decoders reject tag `9`.
19pub const ABI_VERSION: u32 = 5;
20
21/// ABI that introduces [`Value::List`]. [`encode`](super::encode) emits this
22/// only when the chunk contains a list. [`decode`](super::decode) accepts
23/// both v5 and v6.
24pub const ABI_VERSION_LISTS: u32 = 6;
25
26/// A callable entry point inside a [`Chunk`]: either bytecode-defined or a
27/// slot reserved for a native (Rust) function registered with the runtime
28/// via the FFI table.
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub struct FunctionDef {
31    pub name: String,
32    /// Index into `Chunk::code` where execution starts.
33    pub entry: u32,
34    /// Number of parameters. The VM copies them into `r0..arity`
35    /// (exclusive end): arity 2 fills `r0` and `r1`.
36    pub arity: u8,
37    /// Upper bound on registers this function uses; the VM allocates
38    /// exactly this many per call frame instead of a fixed worst-case size.
39    pub num_registers: u8,
40}
41
42/// A compiled unit of Byteflow bytecode: code, constants and the function
43/// table. One `Chunk` can back many concurrently-running flows — it is
44/// immutable after construction, so it is shared behind an `Arc` rather than
45/// copied per flow (see [`crate::Vm`]).
46#[derive(Clone, Debug, Default, PartialEq)]
47pub struct Chunk {
48    pub name: String,
49    pub constants: Vec<Value>,
50    pub code: Vec<Instruction>,
51    pub functions: Vec<FunctionDef>,
52}
53
54impl Chunk {
55    pub fn function(&self, index: u32) -> Option<&FunctionDef> {
56        self.functions.get(index as usize)
57    }
58
59    pub fn constant(&self, index: u32) -> Option<&Value> {
60        self.constants.get(index as usize)
61    }
62
63    /// Number of instructions, used by the verifier to bound-check jump
64    /// targets ahead of time instead of on every branch at runtime.
65    pub fn len(&self) -> usize {
66        self.code.len()
67    }
68
69    pub fn is_empty(&self) -> bool {
70        self.code.is_empty()
71    }
72}