Skip to main content

Bytecode

Struct Bytecode 

Source
pub struct Bytecode {
    pub instructions: Instructions,
    pub constants: Vec<Value>,
    pub source_map: SourceMap,
    pub type_registry: Vec<TypeDef>,
}
Expand description

Compiled bytecode output containing instructions and constants.

This represents the complete compiled program ready for execution by the virtual machine. The Bytecode struct is the interface between the compiler (which produces it) and the VM (which executes it).

§Architecture

The bytecode uses a two-part structure:

  1. Instruction Stream (instructions): A linear sequence of bytecode instructions that the VM executes. Each instruction consists of an opcode byte optionally followed by operand bytes.

  2. Constant Pool (constants): An array of runtime values referenced by OpConstant instructions. The constant pool allows large or frequently-used values to be stored once and referenced by a compact 2-byte index.

§Constant Pool Design

Constants are stored separately from instructions for several reasons:

  • Space efficiency: A large integer like 999_999_999_999 is stored once in the constant pool, not embedded in every instruction that uses it.

  • Fixed instruction size: OpConstant instructions are always 3 bytes (1 opcode + 2 index bytes), regardless of the size of the referenced value.

  • Type flexibility: The constant pool can hold any Value type (integers, booleans, strings, arrays, functions) while the bytecode remains uniform.

§Example

For the expression 1 + 2:

// Constant pool stores the actual values:
let constants = vec![
    Value::Integer(Integer::I64(1)),  // constants[0]
    Value::Integer(Integer::I64(2)),  // constants[1]
];

// Instructions reference constants by index:
let mut instructions = Instructions::new();
instructions.extend(&Instructions::from(encode(Opcode::Constant, &[0])));  // Push constants[0]
instructions.extend(&Instructions::from(encode(Opcode::Constant, &[1])));  // Push constants[1]
instructions.extend(&Instructions::from(encode(Opcode::Add, &[])));        // Add them
instructions.extend(&Instructions::from(encode(Opcode::Pop, &[])));        // Pop result

let bytecode = Bytecode { instructions, constants, source_map: Default::default(), type_registry: vec![] };

When executed by the VM:

  1. OpConstant 0 pushes Value::I64(1) onto the stack
  2. OpConstant 1 pushes Value::I64(2) onto the stack
  3. OpAdd pops both values, adds them, and pushes Value::I64(3)
  4. OpPop removes the result from the stack

Fields§

§instructions: Instructions

The sequence of bytecode instructions to execute.

Each instruction consists of an opcode byte optionally followed by operand bytes. Instructions are executed sequentially by the VM.

§constants: Vec<Value>

The constant pool containing runtime values.

This array holds all constant values referenced by OpConstant instructions. The index into this array is encoded as a 2-byte operand (allowing up to 65,535 distinct constants).

§source_map: SourceMap

Maps instruction byte offsets to source spans for error reporting.

§type_registry: Vec<TypeDef>

Type definitions for user-defined structs and enums.

Registered at compile time and read by the VM for field access, struct construction, and pattern matching operations.

Implementations§

Source§

impl Bytecode

Source

pub fn serialize(&self) -> Result<Vec<u8>, SerializationError>

Serializes this bytecode to a binary representation.

The output can be written to a .mtc file and later restored with deserialize. The format consists of an 8-byte header (magic + version) followed by a postcard-encoded payload.

§Errors

Returns an error if the constant pool contains value types that cannot be represented in the binary format (e.g., Builtin function pointers or tree-walking Function objects).

Source

pub fn deserialize(bytes: &[u8]) -> Result<Self, SerializationError>

Deserializes bytecode from a binary representation produced by serialize.

§Errors

Returns an error if the data is malformed, exceeds resource limits, or contains an unsupported format version.

Trait Implementations§

Source§

impl Clone for Bytecode

Source§

fn clone(&self) -> Bytecode

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Bytecode

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for Bytecode

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl PartialEq for Bytecode

Source§

fn eq(&self, other: &Bytecode) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for Bytecode

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for Bytecode

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,