Skip to main content

Module

Struct Module 

Source
pub struct Module {
    pub chunks: Vec<Chunk>,
    pub native_names: Vec<String>,
    pub entry_point: Option<usize>,
    pub data_layout: Option<DataLayout>,
    pub word_bits_log2: u8,
    pub addr_bits_log2: u8,
    pub float_bits_log2: u8,
    pub wcet_cycles: u32,
    pub wcmu_bytes: u32,
}
Expand description

A compiled Keleusma module.

Fields§

§chunks: Vec<Chunk>

Compiled function chunks.

§native_names: Vec<String>

Declared native function names (from use declarations).

§entry_point: Option<usize>

Entry point chunk index (the main function).

§data_layout: Option<DataLayout>

Data segment layout. If present, defines persistent slots that survive across RESET boundaries.

§word_bits_log2: u8

Word size required by this bytecode, encoded as the base-2 exponent. Actual width in bits is 1 << word_bits_log2. The runtime accepts the bytecode when the recorded value is at most the runtime’s RUNTIME_WORD_BITS_LOG2. The VM masks integer arithmetic to the declared width using sign-extending shift. Mirrored in the framing header for fast pre-decode rejection.

§addr_bits_log2: u8

Address size required by this bytecode, encoded as the base-2 exponent. Actual width in bits is 1 << addr_bits_log2. The runtime accepts the bytecode when the recorded value is at most the runtime’s RUNTIME_ADDRESS_BITS_LOG2. Mirrored in the framing header for fast pre-decode rejection.

§float_bits_log2: u8

Floating-point width required by this bytecode, encoded as the base-2 exponent. Actual width in bits is 1 << float_bits_log2. The runtime accepts the bytecode when the recorded value is at most the runtime’s RUNTIME_FLOAT_BITS_LOG2. The current runtime uses f64 exclusively (exponent 6); narrower or wider floats are reserved for future portability work tracked under B10. Mirrored in the framing header for fast pre-decode rejection.

§wcet_cycles: u32

Declared worst-case execution time per Stream-to-Reset slice, in pipelined cycles. Producer’s claim about the maximum cycles the script consumes between two yield boundaries.

  • 0 means auto: the producer did not declare a value; the runtime computes the bound at load time through its own verifier pass.
  • u32::MAX means overflow: the producer attempted to compute the bound but the result exceeds the field’s range. Programs declaring u32::MAX are rejected at the safe constructor Vm::new because no representable bound exists.
  • Any other value is the producer’s bound. The safe runtime accepts the value as-is; trust skip applies to declared values just as it does to arena capacity.

Mirrored in the framing header for inspection without body decode.

§wcmu_bytes: u32

Declared worst-case memory usage per Stream-to-Reset slice, in bytes. Same 0/u32::MAX conventions as Module::wcet_cycles. Total of stack and heap regions. Mirrored in the framing header.

Implementations§

Source§

impl Module

Source

pub fn to_bytes(&self) -> Result<Vec<u8>, LoadError>

Serialize the module to a self-describing byte vector.

The output begins with the twelve-byte header (magic, version, total length, word size, address size), then the module body in postcard wire format, then a four-byte little-endian CRC-32 trailer. The CRC covers the entire framed range. The algebraic self-inclusion residue of the CRC parameterization makes the trailer part of the checksummed range.

All multi-byte integer fields in the framing are stored in little-endian order. Postcard stores its own multi-byte values in little-endian or as varints. The wire format is therefore identical bytes regardless of producer or consumer host endianness.

Returns LoadError::Codec if postcard rejects any field. The Module type is composed entirely of types that postcard supports, so encode failures are not expected in practice and indicate corruption of the runtime data.

Examples found in repository?
examples/regenerate_zero_copy_bytecode.rs (line 34)
25fn main() {
26    let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
27    let source_path = manifest_dir.join("examples").join("zero_copy_demo.kel");
28    let binary_path = manifest_dir.join("examples").join("zero_copy_demo.kel.bin");
29
30    let source = fs::read_to_string(&source_path).expect("read source");
31    let tokens = tokenize(&source).expect("lex");
32    let program = parse(&tokens).expect("parse");
33    let module = compile(&program).expect("compile");
34    let bytes = module.to_bytes().expect("encode");
35
36    fs::write(&binary_path, &bytes).expect("write binary");
37    println!("wrote {} ({} bytes)", binary_path.display(), bytes.len());
38}
Source

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

Deserialize a module from a self-describing byte slice.

Validation order is truncation, magic, length, CRC residue, version, word size, address size, and body decode. The slice is truncated to the recorded length before the CRC check so that bytecode embedded in a larger buffer is supported. Trailing bytes after the recorded length are ignored.

The CRC is checked before the version, word size, and address size because a corrupted byte in any of those fields would otherwise be reported as a mismatch rather than the more accurate BadChecksum.

Does not run structural verification or resource bounds checks. Pass the result to crate::vm::Vm::new for full verification or to crate::vm::Vm::new_unchecked for trust-based skipping of the bounds checks.

Source

pub fn access_bytes(bytes: &[u8]) -> Result<&ArchivedModule, LoadError>

Validate framing and return a borrowed archived view of the module.

Performs the same framing checks as Module::from_bytes (magic, length, CRC residue, version, word size, address size) and then runs rkyv::access on the body to obtain a &'a ArchivedModule without deserialization.

The body must be 8-byte aligned within the slice. Because the header is sixteen bytes, the body is 8-byte aligned within the slice when the slice base itself is 8-byte aligned. Hosts that compute or load bytecode into an rkyv::util::AlignedVec or a static buffer with #[repr(align(8))] satisfy this requirement. Bytecode placed by the linker into a section that aligns to at least 8 bytes also satisfies it.

Returns LoadError::Codec with an alignment message when the body is not aligned, or when the rkyv structural validator rejects the body. Returns the other LoadError variants for header validation failures.

Source

pub fn view_bytes(bytes: &[u8]) -> Result<Module, LoadError>

Deserialize a module from an aligned byte slice without the AlignedVec copy step that Module::from_bytes performs.

Validates the framing through Module::access_bytes and then calls rkyv::deserialize on the validated archived form. Returns an owned Module for compatibility with the existing execution path. The wire-format validation runs in place against the input slice. The deserialization step still allocates the owned form.

True zero-copy execution against &ArchivedModule is recorded as the next iteration of P10. Path B requires lifetime-parameterizing the Vm and rewriting the execution loop to read from &ArchivedModule. The current view path delivers in-place validation and is the architectural foundation for Phase 2.

Requires the body to be 8-byte aligned. See Module::access_bytes for the alignment contract.

Trait Implementations§

Source§

impl Archive for Module

Source§

const COPY_OPTIMIZATION: CopyOptimization<Self>

An optimization flag that allows the bytes of this type to be copied directly to a writer instead of calling serialize. Read more
Source§

type Archived = ArchivedModule

The archived representation of this type. Read more
Source§

type Resolver = ModuleResolver

The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.
Source§

fn resolve(&self, resolver: Self::Resolver, out: Place<Self::Archived>)

Creates the archived version of this value at the given position and writes it to the given output. Read more
Source§

impl Clone for Module

Source§

fn clone(&self) -> Module

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for Module

Source§

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

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

impl<__D: Fallible + ?Sized> Deserialize<Module, __D> for Archived<Module>

Source§

fn deserialize( &self, deserializer: &mut __D, ) -> Result<Module, <__D as Fallible>::Error>

Deserializes using the given deserializer
Source§

impl<__S: Fallible + ?Sized> Serialize<__S> for Module

Source§

fn serialize( &self, serializer: &mut __S, ) -> Result<<Self as Archive>::Resolver, <__S as Fallible>::Error>

Writes the dependencies for the object and returns a resolver that can create the archived type.

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> ArchivePointee for T

Source§

type ArchivedMetadata = ()

The archived version of the pointer metadata for this type.
Source§

fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata

Converts some archived metadata to the pointer metadata for itself.
Source§

impl<T> ArchiveUnsized for T
where T: Archive,

Source§

type Archived = <T as Archive>::Archived

The archived counterpart of this type. Unlike Archive, it may be unsized. Read more
Source§

fn archived_metadata( &self, ) -> <<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata

Creates the archived version of the metadata for this value.
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> LayoutRaw for T

Source§

fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>

Returns the layout of the type.
Source§

impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
where T: SharedNiching<N1, N2>, N1: Niching<T>, N2: Niching<T>,

Source§

unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool

Returns whether the given value has been niched. Read more
Source§

fn resolve_niched(out: Place<NichedOption<T, N1>>)

Writes data to out indicating that a T is niched.
Source§

impl<T> Pointee for T

Source§

type Metadata = ()

The metadata type for pointers and references to this type.
Source§

impl<T, S> SerializeUnsized<S> for T
where T: Serialize<S>, S: Fallible + Writer + ?Sized,

Source§

fn serialize_unsized( &self, serializer: &mut S, ) -> Result<usize, <S as Fallible>::Error>

Writes the object and returns the position of the archived type.
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.