Expand description
Moonseed implements the Lua 5.4 source language and Lua-visible runtime semantics in safe Rust, with a broad standard library and portable execution checkpoints. Hosts choose libraries, resource limits, and external authority. There is no Lua C API, arbitrary C-module loading, or PUC binary-chunk support. Moonseed binary chunks work across Moonseed native/Wasm targets.
§Quick start
Compile byte source, load it on an idle Runtime, and drive bounded work.
Resume Paused with more fuel; complete Waiting from the host.
use moonseed::{compile, Config, FromLuaMulti, Journal, Runtime, StepOutcome};
let mut config = Config::default();
config.fuel_limit = Some(10_000);
let mut runtime = Runtime::builder().config(config).build()?;
runtime.load_main(&compile(b"return 6 * 7")?)?;
let mut journal = Journal::new();
loop {
match runtime.run(1_000, &mut journal).map_err(moonseed::Error::from)? {
StepOutcome::Paused(_) => continue,
StepOutcome::Completed => break,
other => return Err(format!("unexpected outcome: {other:?}").into()),
}
}
let results = runtime.result_values()?;
assert_eq!(i64::from_lua_multi(results, &mut runtime)?, 42);§Recipe index
The packaged guide contains complete embedding recipes:
- Run a chunk and set limits/libraries.
- Rust callbacks and values and call Lua.
- Host userdata and checkpoint/restore.
- Named errors and tracebacks and async host waits.
§Features and authority
| Cargo feature | Default | Purpose |
|---|---|---|
native-host | yes | Compiles opt-in native adapters; grants no authority by itself. |
counters | no | Unstable instruction counters and JSON reports; never saved in snapshots. |
With default features disabled the core, in-memory filesystem, and mock
capabilities remain available on native and Wasm. Libraries select Lua
functions independently of Cargo features. The builder installs no libraries;
Libraries::STANDARD includes IO/OS functions but excludes debug.
HostCapabilities::sandbox supplies no filesystem, streams, clock, civil-time,
environment, or process authority. Host callbacks and module resolvers are
also capabilities: expose only what a script may access.
§Values and ownership
Value owns primitives or shared roots: LuaString, Table,
Function, Thread, and AnyUserData. Cloning keeps the same Lua
object alive; the last drop releases its root. Roots may outlive the runtime
as Rust objects but cannot be used with a different runtime, including one
restored from its snapshot (ApiError::WrongRuntime). ObjectId is a
snapshot-stable logical identity, not a root or arena index. ValueRef and
StrRef borrow a runtime/context and cannot cross execution. Strings are
bytes; UTF-8 conversions and integer ranges are checked.
FromLua uses strict conversions: f64 accepts numeric values, never a
numeric string. Coerce explicitly opts into Lua coercion. MultiValue
preserves nil holes and distinguishes no results from one nil.
§Host calls, userdata, and hooks
Register stable host symbols with HostRegistry::typed or
HostRegistry::function, then bind Runtime::make_closure into globals.
Lua calls the callback with a borrowed NativeContext. A Rust callback
returns before Lua executes: use NativeContext::call_lua for a
snapshot-backed continuation, and inspect ResumeOutcome on reinvocation.
Runtime::call drives an idle main-thread call with a fuel bound;
CallOutcome::Waiting and CallOutcome::OutOfFuel require continued
run/finish_call, without starting the call again.
HostUserdata payloads are Rust-owned and type checked. Register a
PortableUserdata codec, RebindUserdata key, or a refusing policy.
The collector does not trace arbitrary Rust payloads. Store Lua references
in captures, user values, or owned roots. Mutable UserDataRefMut guards
keep the runtime/context borrowed and update logical charging on drop.
HostRegistry::register_hook installs synchronous bounded profiling
callbacks. HookContext supplies semantic activation metadata without
exposing VM frames or program counters. Host callback state stays outside
snapshots. A native, host-hook, output/warning sink, entropy or module-resolver panic
propagates and poisons execution/snapshots under the default policy; discard the
runtime if the host catches it. NativePanicPolicy::LuaError converts unwinding
native, hook and resolver panics into Lua errors; sinks and other host callbacks
are outside that recovery policy, and partial host effects remain applied.
§Tables and modules
Table::raw_get and NativeContext::raw_get never run __index.
Table::get drives semantic access on an idle main thread. Within a native,
call a Lua accessor (function(t, k) return t[k] end) through
NativeContext::call_lua; this honors table/function __index chains,
errors, host waits, and checkpointed continuations. Do not recursively run
the VM from a callback. ModuleResolver receives exact module-name bytes.
ResolverPolicy::External journals resolution for replay; pure resolvers
must supply immutable answers and be reattached on restore.
§Checkpoints and errors
Runtime::snapshot includes VM globals, active calls, Lua coroutines,
native captures, hooks, pending waits, RNG streams, fuel, and GC state.
Runtime::restore validates before returning a fresh runtime. Host
supplies limits, journal lineage, host callbacks/types/hooks, and capabilities.
Moonseed automatically re-registers its library symbols. Use
Host::libraries to refuse snapshots retaining a disallowed library;
this allowlist grants no external authority and installs no new globals.
Persist the Journal and external resource/dispatch ledger separately.
Restore never undoes external effects or captures the future external world;
exactly-once effects require durable coordination by the embedder.
Snapshot schema 25, bytecode revision 14, table revision 4, fuel revision 7,
GC revision 12, and binary-chunk format 2 are exact version boundaries.
Snapshots are not a durable cross-version save format. Decoding rejects
incompatible revisions, malformed state, missing registrations, denied
libraries, wrong effect domains, and exceeded limits with SnapshotError.
Error distinguishes catchable LuaError, host ApiError, and
execution-integrity VmError. Driving APIs preserve their documented
signatures: an uncaught Lua error is StepOutcome::LuaError; a snapshot
decode failure from restore is Error::Vm(VmError::Snapshot(..)).
Output/error metadata and outcomes marked non_exhaustive need fallback
arms in downstream matches. Input records with public fields retain their
documented construction contract. Deprecated integer-only APIs and
doc(hidden) proof/measurement helpers are outside the 0.1 embedding API.
The latter remain Rust-reachable for workspace native/Wasm qualification.
Explore api for rooted operations and hostcaps for capability
contracts and deterministic backends. The repository embedding guide and
ten executable examples provide lifecycle and sandbox recipes.
The library MSRV is Rust 1.88. Minor 0.x releases may raise it with a
changelog entry. See the compatibility policy
for Rust API, Lua semantics, format and determinism boundaries.
Re-exports§
pub use api::AnyUserData;pub use api::ApiError;pub use api::CallOutcome;pub use api::Coerce;pub use api::Completion;pub use api::ConversionError;pub use api::Error;pub use api::FromLua;pub use api::FromLuaMulti;pub use api::Function;pub use api::FunctionKind;pub use api::HookAction;pub use api::HookContext;pub use api::HookEvent;pub use api::HookFunction;pub use api::HookInfo;pub use api::HookMask;pub use api::HookSettings;pub use api::Host;pub use api::HostCapabilities;pub use api::HostEnv;pub use api::IntoLua;pub use api::IntoLuaMulti;pub use api::Libraries;pub use api::LuaError;pub use api::LuaString;pub use api::MemoryErrorPolicy;pub use api::ModuleResolver;pub use api::MultiValue;pub use api::NativeContext;pub use api::NativePanicPolicy;pub use api::NativeReturn;pub use api::Resolved;pub use api::ResolverPolicy;pub use api::Result;pub use api::Resume;pub use api::ResumeOutcome;pub use api::RuntimeBuilder;pub use api::StrRef;pub use api::Table;pub use api::TableTraversal;pub use api::Thread;pub use api::ThreadStatus;pub use api::TraversalBudget;pub use api::UserDataRefMut;pub use api::Value;pub use api::ValueRef;pub use api::Variadic;pub use api::WaitInfo;pub use api::WaitRequest;pub use host::EffectId;pub use host::EffectRecord;pub use host::HostRegistry;pub use host::HostValue;Deprecated pub use host::Journal;pub use host::JournalError;pub use host::JournalPayload;pub use host::LegacyCompletion;Deprecated pub use host::LuaType;pub use host::NativeCall;Deprecated pub use host::NativeFn;pub use host::NativeOutcome;pub use host::NativePolicy;pub use host::NativeValue;pub use host::RawSetError;pub use host::UserdataError;pub use host::Warnings;pub use hostcaps::CapabilityPoll;pub use hostcaps::CapabilityRequest;pub use hostcaps::CapabilityValue;pub use hostcaps::CivilOffset;pub use hostcaps::CivilTime;pub use hostcaps::Clock;pub use hostcaps::Completion as CapabilityCompletion;pub use hostcaps::EffectClass;pub use hostcaps::Environment;pub use hostcaps::Filesystem;pub use hostcaps::HandlePolicy;pub use hostcaps::HostIoError;pub use hostcaps::HostIoErrorKind;pub use hostcaps::MemoryFilesystem;pub use hostcaps::MemoryOptions;pub use hostcaps::OpenMode;pub use hostcaps::PendingToken;pub use hostcaps::PipeMode;pub use hostcaps::Process;pub use hostcaps::ProcessStatus;pub use hostcaps::ResourceId;pub use hostcaps::Stdio;pub use hostcaps::Stream;pub use hostcaps::memory_filesystem;pub use hostcaps::NativeFilesystem;pub use hostcaps::NativeOptions;pub use hostcaps::native_host;
Modules§
- api
- Rooted embedding operations; also re-exported at the crate root. Owned and borrowed embedding values (ADR 0053).
- convenience
- Bounded embedding helpers; existing runtime policies remain explicit. Small embedding operations with explicit fuel, journal and host policy. A fuel quantum bounds VM execution, not Rust callbacks or wall-clock time. Pauses and waits require application action; helpers never retry or clean up.
- guide
- Using Moonseed
- hostcaps
- Explicit, optional host authority and deterministic reference backends. Explicit host authority for filesystem, streams, time, environment and processes.
- portable_
math - Shared floating-point reference for hosts that need bit-identical math.
Structs§
- Compile
Error - A compilation failure with its source range and diagnostic.
- Compile
Limits - Compiler output bounds. Larger values are clamped to the structural ceilings; memory grows with the input, never with these limits.
- Compiled
Chunk - Detached compiled chunk. Instruction spans are debug metadata: they are not installed into the VM and they are not part of a snapshot.
- Config
- Runtime configuration, resource limits, and deterministic execution policy.
- Effect
Id - Host-owned lineage. Exact restore keeps it; a future fork would mint a new one.
- Effect
Record - One persisted journal outcome and its request identity.
- Host
Light Key - A light userdata key the host chooses (ADR 0043). Moonseed promises only identity: two light userdata are equal when their keys are, and never equal a token the VM makes. The bits are not an address; a host that maps keys to its own resources keeps that map. Unstable API.
- Host
Registry - Host native callbacks and userdata registrations, bound by stable symbols.
Cloning shares callback objects, not mutable registration maps. A runtime
owns its registry; Lua captures belong in
crate::Runtime::make_closure, while Rust callback state remains host-owned and is not checkpointed. Rebuild host registrations beforecrate::Runtime::restore; Moonseed supplies its allowed library symbols throughcrate::Host. Missing symbols fail withcrate::SnapshotError::UnknownHostSymbol; userdata codecs and policies must match. Typed argument failures become catchable Lua errors; other misuse remainscrate::ApiError. Callback panics propagate and poison execution/snapshots: discard the runtime if the host catches one. - Journal
- Map from effect id to the outcome that was committed.
- Journal
Error - A journal payload mismatch. No callback is repeated on a mismatch.
- Light
Userdata - A light userdata as the host sees it: an opaque, copyable identity. A host key comes back as it went in; a token the VM made can be handed back in, never forged. Unstable API.
- Limits
- Every resource dimension a runtime is bounded in (ADR 0052): what it
runs under, and what a checkpoint is restored into
(
Runtime::from_snapshot_with_limits). The defaults areConfig::default’s. - Memory
Usage - What the heap holds and when the next automatic collection runs. Sizes are logical bytes (ADR 0021), not bytes of host memory.
- Native
Value - A Lua value inside one native call. It cannot outlive the call: the
lifetime ties it to the
NativeCallit came from, and no collection runs while a native function runs. - Object
Id - Logical identity of a heap object. Never reused, never a memory address.
- Rebind
Error - A resource could not be rebound. The message describes the host failure.
- Root
- Strong host-owned GC root. Keeps its target alive until released.
- Runtime
- A single-threaded Lua runtime with rooted values and portable checkpoints.
It is neither
SendnorSync; drive and complete waits on its owning thread. It owns Lua state, not the host’sHostRegistrycallbacks, shared capability backends, orJournalpersistence. Ownedcrate::Valueroots keep objects alive; borrowed views cannot cross a mutable execution call. - Span
- Byte range
[start, end)into the source that produced it. - WaitKey
- The identity of a pending host wait. Completion validates it against the runtime.
Enums§
- Compile
Error Kind - The category of a source compilation failure.
- Exit
Status - A requested process status, without imposing a host platform’s exit constants.
- GcMode
- How the collector works (ADR 0050, ADR 0051).
- Host
Value Deprecated - A Lua value as the host sees it or hands it in. Unstable API.
- Iteration
Profile - Raw table traversal policy. This is host configuration, not snapshot state.
- Legacy
Completion Deprecated - How the host ends a native call that is waiting (
Runtime::complete). Unstable API. - LuaFault
- The class of a Lua error: every error Lua code can catch with
pcall(ADR 0024). The error object itself is a Lua value; for every class butErrorit is the class’s reserved message string (LuaFault::text). Internal corruption and host misuse areVmError, never aLuaFault. - LuaType
- The Lua type of a value, as
type()names it. - Native
Outcome - What a native function asks the VM to do after it returns.
- Native
Policy - How a native function relates to state outside the VM.
- Pause
Reason - Why execution paused without yielding.
- RawSet
Error - Why
NativeCall::raw_setrefused. - Root
Error - A legacy explicit-root operation failed.
- Snapshot
Error - A snapshot could not be written or restored.
- Step
Outcome - The state reached after driving the executor.
- Termination
Reason - A fatal execution limit stopped the runtime.
- Userdata
Error - Why a userdata operation of a
NativeCallrefused. Unstable API. - Userdata
Policy - A registered host type’s snapshot policy.
- VmError
- An execution, integrity, snapshot, or host API failure.
- Wait
Error - A legacy wait completion failed.
Constants§
- MAX_
REBIND_ KEY - Maximum serialized external key for rebindable userdata.
Traits§
- Host
Userdata - A Rust type whose values Lua can hold as full userdata.
- Journal
Payload - Payloads accepted by
Journal::commit: integers and byte vectors. Both forms fail on a payload kind mismatch without repeating the callback. - Portable
Userdata - A host userdata type with a deterministic codec.
- Rebind
Userdata - A host handle whose stable key is resolved against resources already owned by the host. Rebinding receives no runtime, Lua context, or journal.
Functions§
- compile
- Compile with the default source and code limits.
- compile_
named - Compile with authored identity on both successful chunks and syntax errors.
- compile_
named_ with_ limits - Compile with authored identity and the same clamped compiler bounds as
compile_with_limits. Naming never raises the source/code limits. - compile_
with_ limits - Compile with configurable bounds, clamped to the structural ceilings.
- line_
col - 1-based line and 1-based byte column.
\n,\r,\n\r, and\r\nare each one line break. The column counts bytes, not Unicode scalar values. - register_
base - Register the base functions under their
base.*symbols, and the iteratoripairsreturns. - register_
coroutine - Register the
coroutinefunctions. - register_
debug - Register the
debugfunctions. - register_
io - Register the IO functions and internal file methods; grants no authority.
- register_
math - Register the
mathfunctions under theirmath.*symbols. - register_
os - Register the OS library. Installation grants no host authority.
- register_
package - Register
require, the preload searcher, and the optional host searcher. - register_
standard - Register the base library,
math,table, andstring: every functionRuntime::install_standardinstalls. - register_
string - Register the
stringfunctions, the string metatable’s metamethods, andgmatch’s iterator. - register_
table - Register the
tablefunctions under theirtable.*symbols. - register_
utf8 - Register UTF-8 functions and the two stable iterator values.
Type Aliases§
- Native
Call Deprecated - Arguments in, results out, for one native call. Unstable API.
- Native
Fn - A native function. It must not call back into Lua.
- Warnings
- Where warnings go (ADR 0049):
warn’s and those of failed finalizers. Host state, like the output sink. A warning is one external effect, given to the sink as pieces; the flag is Lua’stocont, true for every piece but the last. Control messages (a single piece starting with@, such as@onand@off) are passed on: what they mean is the sink’s choice, as it is the warning function’s in Lua. Unstable API.