Skip to main content

Crate keleusma

Crate keleusma 

Source
Expand description

Keleusma is a Total Functional Stream Processor that compiles to bytecode and runs on a stack-based virtual machine. The crate targets no_std + alloc environments and is designed for embedded scripting where definitive worst-case execution time and worst-case memory usage bounds matter.

The crate has no built-in standard library. All domain functionality is provided by host-registered native functions through vm::Vm::register_fn, vm::Vm::register_native, and the related entry points. The bundled libraries in stddsl are examples of the registration pattern, not a closed set.

§Quick start

// Requires the `compile` cargo feature (default on).
use keleusma::compiler::compile;
use keleusma::lexer::tokenize;
use keleusma::parser::parse;
use keleusma::vm::{DEFAULT_ARENA_CAPACITY, Vm, VmState};
use keleusma::{Arena, Value};

let source = r#"
    fn double(x: Word) -> Word { x * 2 }
    fn main(n: Word) -> Word { n |> double() }
"#;

let tokens = tokenize(source).expect("lex");
let program = parse(&tokens).expect("parse");
let module = compile(&program).expect("compile");
let arena = Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
let mut vm = Vm::new(module, &arena).expect("verify");

match vm.call(&[Value::Int(21)]).unwrap() {
    VmState::Finished(value) => println!("{:?}", value),
    _ => unreachable!(),
}
// prints: Int(42)

§Cargo features

The crate exposes orthogonal feature gates so hosts can strip pipeline stages they do not need.

  • compile (default on): lexer, parser, type checker, monomorphizer, compiler. Drop when the host ships precompiled bytecode.
  • verify (default on): structural verifier and WCET/WCMU resource-bounds pass. With this off, vm::Vm::new behaves like vm::Vm::new_unchecked.
  • floats (default on): the Float surface type, Value::Float, Op::IntToFloat/FloatToInt, and the audio_natives and stddsl::Math/stddsl::Audio bundles. Drop to eliminate the soft-float compiler_builtins routines from the runtime image.
  • signatures (default off): Ed25519 module signing and load-time verification.
  • shell (default off): the stddsl::Shell bundle. Requires std.
  • sdl3-example (default off): builds the bundled SDL3 audio piano-roll example. cmake-builds SDL3 from source.

Seven mutually-exclusive narrow-word-*, narrow-address-*, and narrow-float-32 parametric-runtime selectors gate the framing-level upper bound on bytecode widths for hosts that ship only a sub-64-bit GenericVm instance.

§Further reading

The repository’s README.md and docs/ knowledge graph describe the language design, execution model, instruction set, wire format, and conservative-verification stance in depth.

Re-exports§

pub use kstring::KString;
pub use address::Address;
pub use bytecode::CostModel;
pub use bytecode::GenericValue;
pub use bytecode::Module;
pub use bytecode::NOMINAL_COST_MODEL;
pub use bytecode::OpCost;
pub use bytecode::OpCostContext;
pub use bytecode::VALUE_SLOT_SIZE_BYTES;
pub use bytecode::Value;
pub use bytecode::nominal_op_cycles;
pub use float::Float;
pub use marshall::IntoFallibleNativeFn;
pub use marshall::IntoNativeFn;
pub use marshall::KeleusmaType;
pub use marshall::RefContext;
pub use opaque::HostOpaque;
pub use opaque::host_arc;
pub use text_size::TextSize;
pub use text_size::op_cost_context;
pub use vm::NativeCtx;
pub use vm::OverflowPolicy;
pub use vm::VerifyWarning;
pub use vm::VmError;
pub use vm::VmOptions;
pub use vm::WarningKind;
pub use word::Word;

Modules§

address
Address-type abstraction used by the parametric vm::GenericVm to model the runtime’s address width. Parametric address-value abstraction for sub-64-bit native runtimes (B16). The wire-format header’s addr_bits_log2 field declares the script-visible address width; this trait lifts that width into the type system so the parametric Vm<W, A, F> can specialize its address values to the target’s pointer width.
ast
Abstract syntax tree node definitions.
audio_natives
Bundled audio-DSP natives (audio::midi_to_freq, audio::db_to_linear, and similar). Requires the floats feature. Built-in audio native functions for digital signal processing.
bytecode
Runtime values, instructions, the Module type, and the cost model.
compiler
AST to bytecode emission.
debug_meta
Strippable debug metadata: the chunk-local debug_meta::DebugPool section and its canonical byte encoding. Parallel infrastructure for B29; the foundational data model and serialization, not yet attached to bytecode::Chunk nor emitted by the compiler. Strippable debug metadata (backlog item B29).
encryption
Authenticated encryption of compiled Modules under the optional encryption feature. Implements the V0.2.1 hybrid asymmetric key wrapping (X25519 ECDH plus HKDF-SHA-256 plus AES-256-GCM). Feature-gated because the crypto stack adds meaningful binary footprint for hosts that do not need it. Authenticated encryption layer for compiled Keleusma modules.
flat_value
Flat-byte composite representation helpers and the flat_value::FlatComposite byte buffer for B28’s runtime composite-value refactor. A composite value is pure bytes; the field offsets are baked into the access instructions by the compiler, so the buffer carries no layout reference. Flat-byte composite representation for Keleusma values.
float
Parametric floating-point trait used by vm::GenericVm. The trait and its f32 and f64 impls are always compiled so the generic shape carries a Float type parameter regardless of the floats feature; the floating-point variants of Value and the floating-point opcodes remain gated by floats. Parametric floating-point abstraction for sub-64-bit native runtimes (B16). The wire-format header’s float_bits_log2 field declares the script-visible float width; this trait lifts that width into the type system so the parametric Vm<W, A, F> can specialize its floating-point values to the target’s float width.
interval
Closed-signed-interval lattice over i64 used by the type checker and the refinement-elision pass. Interval-arithmetic primitive used by the refinement-elision pass (B13 Tier 3) and reserved for future helper-function WCMU analysis (B12) and CallIndirect flow analysis (B14).
kstring
Arena-resident dynamic strings (KString) at the host-VM boundary. Arena-backed dynamic-string handle for the Keleusma runtime.
layout_pass
Compile-time layout pass. Bridges AST type expressions to the value_layout::LayoutDescriptor byte-layout descriptors used by subsequent B28 phases for composite allocation and field access. Compile-time layout pass.
lexer
Source-text tokenisation (lexer).
marshall
Type-driven marshalling between host Rust types and runtime Values for native function registration. Static marshalling between Rust types and the runtime GenericValue enum.
monomorphize
Compile-time monomorphization of generic functions, structs, and enums. Compile-time monomorphization for generic functions.
opaque
Opaque host-value support: the opaque::HostOpaque trait and the opaque::host_arc constructor that produces Value::Opaque(Arc<dyn HostOpaque>). Host-supplied opaque types referenced from Keleusma scripts.
parser
Token-to-AST recursive-descent parser.
shared_buf
The unsafe API layer for the borrowed host-owned shared-data buffer (B28 item 2). All raw-pointer code in the shared-data path is confined to shared_buf::SharedBuf; the rest of the runtime works with safe slices. The host-owned shared-data buffer borrowed for one call/resume (B28 item 2 shared-data re-architecture).
stddsl
Bundled standard-library DSLs (stddsl::Math, stddsl::Audio, stddsl::Shell) registered through vm::Vm::register_library. Standard DSL libraries packaged as host-registerable bundles.
target
Target descriptor (word/address/float widths, endianness) used by compiler::compile_with_target for cross-architecture portability. Target descriptor for cross-architecture portability.
text_size
Abstract-interpretation text-size lattice used by the WCMU pass for dynamic-text allocations. Abstract interpretation lattice for tracking text-size bounds through Keleusma bytecode.
token
Token definitions and keyword recognition.
typecheck
Hindley-Milner type checker with generics, traits, and bounds. Static type checker for Keleusma source programs.
utility_natives
Bundled utility natives. V0.2.0 ships only println here; other utilities are host-registered.
value_layout
Layout descriptors for composite Keleusma values. Parallel infrastructure for B28’s runtime composite-value representation refactor. Not yet consumed by the runtime. Layout descriptors for composite Keleusma values.
verify
Structural verifier plus WCET and WCMU resource-bounds pass.
verify_typed
Phase 0 spike for the A.2.1 typed operand-stack verifier pass. Not yet wired into verify; a standalone proof of concept for the abstract operand-stack domain and baked-offset validation. Typed operand-stack verifier pass (A.2.1) — the abstract interpreter.
visitor
Visitor and mutable-visitor traits with default walk methods over the AST. AST visitor traits with default-implemented structural walks.
vm
The stack-based virtual machine and its coroutine driver.
wire_format
Wire-format encoding and decoding of compiled Modules. V0.2.0 wire format types and codec.
word
Word-type abstraction used by the parametric vm::GenericVm to model the runtime’s word width. Parametric integer-word abstraction for sub-64-bit native runtimes (B16). The bundled Vm defaults to Word = i64, but hosts targeting narrower runtimes (16-bit Vm<i16, ...> for retro-class hardware, 8-bit Vm<i8, ...> for the smallest microcontrollers) construct a Vm with the appropriate integer width.
zero_value
Canonical zero value per type and lowest-valid resolution for refined newtypes. Parallel infrastructure for B35’s Partial Operation Handling; native code generation is the intended consumer. Not yet consumed by the runtime. Canonical zero value and lowest-valid resolution.

Structs§

Arena
A dual-end bump-allocated arena.
ArenaHandle
Lifetime-free safe handle to a value stored in an arena.
BottomHandle
Allocation handle for the bottom end of an arena.
Budget
A worst-case memory usage budget.
EpochSaturated
Hard halt error returned by Arena::reset when the epoch counter would saturate.
Stale
Error returned by ArenaHandle::get when the arena has been reset since the handle was issued.
TopHandle
Allocation handle for the top end of an arena.

Derive Macros§

KeleusmaError
Derive From<E> for keleusma::VmError for a fieldless (discriminant-only) enum, producing a keleusma::VmError::NativeErrorCode whose code is the variant’s discriminant (B35 P7). The reference is a plain code span because this proc-macro crate does not depend on keleusma, so an intra-doc link cannot resolve the path.
KeleusmaType
Derive keleusma::KeleusmaType for a struct or enum.