Skip to main content

Module runtime

Module runtime 

Source
Expand description

Shared wasmtime primitives used by every host of nomiscript-compiled modules: the entity-script ScriptExecutor and the rpc eval channel.

Owns the engine config (WasmGC + epoch interruption + optional fuel), the per-bytecode Module cache, the trap-classification helper, and the decode_eval_result helper that walks the nomi-eval (ref null any) return value into a structured EvalValue. Higher-level consumers parameterize over the Store data type and assemble their own Linker on top.

Structs§

EngineOpts
HostCondition
A structured failure a native returns as its host Err. The classifier lifts it from the wasmtime error chain with code and detail intact.
ModuleCache
Per-engine bytecode cache keyed by the full module bytes. Cloning a ModuleCache yields a handle into the same inner map; meant to be shared between long-lived hosts (Session, ScriptExecutor) and any per-form helpers that need the same cached compilation.
ScriptRaise
An uncaught in-guest condition. detail is the decoded detail value, None when absent.
StructView
The name and fields of a DEFSTRUCT instance; boxed in EvalValue so the error types carrying a value stay small.
TypeHandles
Module type handles for classifying a heterogeneous anyref result or $pair car by structural kind (ADR-0033 Phase 6), once the null / $t / i31 kinds Phase 3 already covers are ruled out. WasmGC struct/array types are structural, so the host can’t name “the ratio type”; instead it reads the HeapType off an export whose signature already carries it — no value is ever taken through any of these exports host-side, only their declared shape. ratio_new / commodity_new / pair_new / string_eq / symbol_new and one alloc_<kind> per nomiscript::EntityKind with a field layout are exported by every module regardless of program content.

Enums§

EngineError
EvalValue
Final value captured by an eval-mode module via the nomi_capture_* host fns. Mirrors the subset of nomiscript::WasmType variants the compiler emits as terminal stack types, plus a Bytes variant for native fns that marshal compound data (server-command results via scripting-format, chart SVGs, exported files, etc.). Cons/Vector/Closure/Struct still wait for the GC migration.
ProfilerStrategy
Optional profiling strategy. JitDump is the Linux perf record flow; it writes a jit-<pid>.dump file the OS-level profiler can read. PerfMap is the simpler symbol-name-only Linux variant. Both require the wasmtime/profiling cargo feature, which we pull in via the jitdump feature flag on the scripting crate; non-Linux builds should leave this as None.
UnitEnd
How a unit ended, which decides what its globals hold.

Constants§

MAX_WIRE_LIST_DEPTH
Deepest list and struct nesting a script’s result may have: the guest writes a placeholder past it, so a struct holding itself ends, and the host decoder refuses it. A client reader counts every expression, so the (:id N :value V) envelope and the atom inside the innermost list take two of its levels (nomiscript::MAX_READ_DEPTH).

Functions§

alloc_commodity_ref
Allocates an ATOMIC $commodity value by re-entering the guest’s exported commodity_new with the four i64 components (numer, denom, commodity_hi, commodity_lo). Since ADR-0028 E0 the $commodity struct carries a 5th (ref null $unit_term) field; the host must NOT construct that ref-bearing struct itself, so it delegates to the guest helper (which sets the term to null = atomic) — the same re-entry pattern as alloc_pair_chain / the entity allocators. Async because it calls back into the wasm instance.
alloc_entity_via_export
Allocates an entity wasm struct ($account, $commodity_entity, etc) by re-entering the module’s exported alloc_<kind> function. The host can’t freshly construct an entity StructType via StructType::new — fields like (ref null $i8_array) reference concrete type indices that engine canonicalization compares by identity, so any abstract anyref-typed fresh declaration produces a structurally distinct (and uncastable) type. Re-entry through the guest’s own allocator (registered in CompileContext::register_entity_allocators) sidesteps the issue: each call returns a struct ref of the exact $<kind> type the subsequent ref.cast (ref $<kind>) in the consuming form accepts.
alloc_pair_chain
Folds an iterator of GC-ref elements into a $pair chain by re-entering the wasm module via its exported pair_new function. Returns the chain head, or None if the iterator is empty.
alloc_ratio_ref
Allocates a $ratio wasm struct (2 i64 fields: numer, denom). Mirrors alloc_commodity_ref for the Ratio numeric stratum — used when a host fn returns a typed Ratio without going through the synthesized ratio_new wrap.
alloc_string_ref
Allocates a $i8_array wasm array holding bytes and returns a rooted reference. Single allocation; callers can format UUID/name payloads into a reused Vec<u8> and ship the bytes without an intermediate String. Engine canonicalizes the i8 array type so the host-side allocation matches the guest’s (array i8) declaration in CompileContext::new_skeleton.
alloc_value
The guest value of value: strings, numbers, t, nil, symbols and lists of them.
build_engine
call_i64_export
Instantiates module against an empty linker and calls a zero-arg export returning a single i64. Constraints (fuel cap, epoch deadline) come from the caller-supplied Store.
carry_globals
Takes the unit’s manifest and settles each slot it wrote: one none of whose flags is 1 never got the unit’s value and is put back as it was before the unit, a function or layout keeps the last definition that ran, and a cell that got a value carries the one its instance holds, or, when the unit trapped inside a binding of it, the one outside the binding; one only a DEFVAR of it reached stays declared special and unbound. Never fails the unit that ran: a cell that cannot be read becomes an opaque global, loud when a later unit reads it, and the cause is logged. The session heap is settled only once the unit’s instance prologue ran to its end.
carry_not_run
Puts back every slot a unit wrote when it compiled but never ran: its instantiation failed, or an interrupt stopped it before its call.
classify_runtime_error
Classifies a [wasmtime::Error] thrown during execution into a typed EngineError. Order: [wasmtime::Trap] (fuel/epoch), a HostCondition or ScriptRaise in the chain, then the fiber cap; the rest falls through as Trap(message).
compile_module
compile_wat
decode_eval_result
Decodes nomi-eval’s anyref return value into an EvalValue using the compile-time-known result type. None for the result_ty means the form was empty / definition-only and the host should see EvalValue::Nil. Numeric types (I32, Ratio, Commodity) and StringRef decode directly. PairRef walks the chain, decoding each car per its declared element type. EntityRef returns a placeholder until a downstream consumer needs the structured shape host-side. Takes any AsContextMut so it works with both &mut Store<T> (sync test paths) and &mut Caller<'_, T> (async host fn paths). handles resolves the module’s $t singleton and struct/array type handles (see super::type_handles::resolve_type_handles), needed to classify a heterogeneous AnyRef result by identity/kind (ADR-0033).
err_code_and_message
Maps an EngineError to the (code, message) pair scripts and batch consumers see when a script fails — code is a kebab-case symbol (matching the wire envelope’s :code slot for catch-each cells and server::script per-tx reports), message is the engine’s own diagnostic string.
logged_values
The one log message for args, a $pair list of the printed values: each printed princ-style, joined by a space. None when a value in it cannot be read (compound money, a value of no known kind): the caller reports that to the guest, never as text.
nomi_raise
The __nomi_raise host fn body shared by every linker: reads the condition’s fields and always returns Err, carrying a ScriptRaise unless the code or message cannot be read.
read_commodity_arg
Reads a $commodity arg ref into its (numer, denom, commodity_id) components. Mirrors read_string_arg for the Commodity numeric stratum: fields 0-1 are numer/denom, fields 2-3 are the UUID halves. None returns for a null ref; bad shape surfaces as a structured trap.
read_entity_string_field
Reads a named String field from an entity struct arg, resolving the field’s slot index from nomiscript::entity_layout (the single source of struct slot order). None returns for a null ref. Errors if the kind has no layout, the named field is absent or non-String, or the slot is not an $i8_array. This is how the draft natives read e.g. an account’s id (slot 0) from a (get-account …) entity ref passed as an argument.
read_entity_string_field_ctx
Context-based core of read_entity_string_field, split out so it is unit-testable without a Caller (tests hold a bare Store). Resolves the field’s slot from the entity layout and reads it as an $i8_array string.
read_ratio_arg
Reads a $ratio arg ref into its (numer, denom) components. None returns for a null ref; a non-positive denominator is a structured trap. Mirrors read_commodity_arg for the dimensionless Scalar stratum (a draft-split amount).
read_string_arg
Reads a $i8_array arg ref into a Rust String. None is returned for null refs (the wasm-level (ref null $i8_array) param’s null state). The underlying byte storage is i8 (mutable per register_type("i8_array")), so each element is read via array.get_u semantics and assembled into a Vec<u8> then UTF-8 validated. Non-UTF-8 bytes surface as a structured trap rather than a silent replacement.
resolve_caller_type_handles
resolve_type_handles for a host function, which sees its calling instance’s exports only through the Caller.
resolve_type_handles
Resolves TypeHandles from instance’s exports. Call once per eval call, alongside (in place of) t_singleton.
t_singleton
Resolves the compiler-emitted t singleton export (ADR-0033: the $t module global, an empty-struct instance identified by reference equality) so the host can recognise it when decoding an AnyRef result or list cell. Every module the compiler emits exports it, so a missing export is a structured error, not a silent fallback.
throw_condition
Throws a $nomi_error carrying code (upper-cased, as handler-case compares it), message and the structured detail, so the calling script’s handler-case can catch it and read the detail with error-detail. Return the result from the host fn: return Err(throw_condition(&mut caller, code, message, &detail).await). Any failure while building the condition is returned in its place.