1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
use std::ops::{BitOr, BitOrAssign};
use crate::{Config, HostRegistry, Limits, Runtime};
use super::Result;
/// Standard libraries selected at construction or allowed on restore. `STANDARD` omits debug;
/// the default builder installs no libraries.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Libraries(u16);
impl Libraries {
/// No libraries.
pub const NONE: Self = Self(0);
/// Base globals.
pub const BASE: Self = Self(1);
/// Package and require.
pub const PACKAGE: Self = Self(2);
/// Coroutine library.
pub const COROUTINE: Self = Self(4);
/// Math library.
pub const MATH: Self = Self(8);
/// Table library.
pub const TABLE: Self = Self(16);
/// String library and its type metatable.
pub const STRING: Self = Self(32);
/// Debug library.
pub const DEBUG: Self = Self(64);
/// Supported libraries other than debug.
pub const STANDARD: Self = Self(959);
/// Every supported library, including debug.
pub const ALL: Self = Self(1023);
/// UTF-8 byte operations.
pub const UTF8: Self = Self(128);
/// IO library; grants no host filesystem or stream authority.
pub const IO: Self = Self(256);
/// OS library; grants no authority.
pub const OS: Self = Self(512);
pub(crate) fn register(self, registry: &mut HostRegistry) {
macro_rules! register {
($flag:ident, $function:path) => {
if self.contains(Self::$flag) {
$function(registry);
}
};
}
register!(BASE, crate::register_base);
register!(PACKAGE, crate::register_package);
register!(COROUTINE, crate::register_coroutine);
register!(MATH, crate::register_math);
register!(TABLE, crate::register_table);
register!(STRING, crate::register_string);
register!(UTF8, crate::register_utf8);
register!(DEBUG, crate::register_debug);
register!(OS, crate::register_os);
register!(IO, crate::register_io);
}
pub(crate) fn contains(self, other: Self) -> bool {
self.0 & other.0 == other.0
}
}
impl BitOr for Libraries {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl BitOrAssign for Libraries {
fn bitor_assign(&mut self, rhs: Self) {
*self = *self | rhs;
}
}
/// Host policy for resource failures reported as Lua memory errors.
/// This policy is supplied again on restore; it is not snapshot state.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum MemoryErrorPolicy {
/// Lua memory errors remain catchable by protected calls (Lua 5.4 default).
#[default]
Catchable,
/// Resource memory errors terminate execution, bypassing all Lua handlers.
/// Includes logical heap, object count and string allocation limits.
Terminal,
}
/// Host policy for panics at native callback boundaries.
/// Supplied again on restore; this is not snapshot state.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum NativePanicPolicy {
/// Propagate Rust panics to the host. The runtime must then be discarded.
#[default]
Poison,
/// Catch unwinding panics and raise a Lua string error at the call site.
/// String payloads become `native panic: <payload>`; other payloads become
/// `native panic: non-string payload`. Partial native effects stay applied.
/// Also applies to natives in `__gc`, `__close`, and hooks, and registered
/// host hooks and module resolvers. A userdata charge measurement panic
/// refuses recovery and poisons the runtime; discard it after catching the
/// panic at the host. Other host callbacks are outside this policy. Rust's panic
/// hook still runs. Panics cannot be caught with `panic = "abort"` (including
/// typical wasm targets), and aborts or panicking destructors can still exit.
LuaError,
}
/// Construction policy and optional host capabilities (ADR 0053).
#[derive(Default)]
pub struct RuntimeBuilder {
pub(crate) exposed: Vec<String>,
pub(crate) config: Config,
pub(crate) memory_error_policy: MemoryErrorPolicy,
pub(crate) native_panic_policy: NativePanicPolicy,
pub(crate) registry: HostRegistry,
pub(crate) libraries: Libraries,
pub(crate) capabilities: super::HostCapabilities,
pub(crate) package_path: Vec<u8>,
pub(crate) package_cpath: Vec<u8>,
}
impl RuntimeBuilder {
/// Register a typed callback and publish it under the same global name at
/// build time, using raw assignment without Lua execution. Existing builder
/// policy is preserved. As with `typed`, reusing a symbol replaces it;
/// a later `registry` call replaces these registrations too.
///
/// ```
/// use moonseed::{*, convenience::*};
/// let mut rt = Runtime::builder().expose("double", NativePolicy::VmLocal, |_, n: i64| Ok(n * 2)).build()?;
/// let double = rt.globals().raw_get::<_, Function>(&mut rt, "double")?;
/// assert!(matches!(rt.call::<i64>(&double, 21, &mut Journal::new(), 1000)?, CallOutcome::Done(42)));
/// # Ok::<(), EmbedError>(())
/// ```
pub fn expose<A, R, F>(
mut self,
name: impl Into<String>,
policy: crate::NativePolicy,
f: F,
) -> Self
where
A: crate::FromLuaMulti,
R: crate::IntoLuaMulti,
F: Fn(&mut crate::NativeContext<'_>, A) -> crate::Result<R> + 'static,
{
let name = name.into();
self.registry.typed(name.clone(), policy, f);
self.publish_on_build(name);
self
}
fn publish_on_build(&mut self, name: String) {
if !self.exposed.contains(&name) {
self.exposed.push(name);
}
}
/// Register T with the snapshot-refusing policy if absent. Never replace an
/// existing registration: a different policy, symbol or type is `WrongType`.
/// Allocate/publish instances with `create_host_userdata` after one build.
///
/// ```
/// struct Counter(i64);
/// impl moonseed::HostUserdata for Counter {
/// const SYMBOL: &'static str = "app.Counter";
/// fn logical_size(&self) -> u64 { 8 }
/// }
/// let mut rt = moonseed::Runtime::builder().userdata::<Counter>()?.build()?;
/// # let counter = rt.create_host_userdata(Counter(41), 0)?;
/// # Ok::<(), moonseed::Error>(())
/// ```
pub fn userdata<T: crate::HostUserdata>(mut self) -> Result<Self> {
if let Some(entry) = self.registry.userdata_type(T::SYMBOL) {
if entry.type_id != std::any::TypeId::of::<T>()
|| entry.policy.kind() != crate::UserdataPolicy::Refuse
{
return Err(crate::ApiError::WrongType.into());
}
} else if self.registry.has_userdata_type::<T>() {
return Err(crate::ApiError::WrongType.into());
} else {
self.registry.register_userdata::<T>();
}
Ok(self)
}
/// Register and publish a serializable wait callback. Arguments become the
/// request payload. No Future, executor, implicit reply, or Lua execution is
/// installed; the application dispatches the operation and supplies a reply.
///
/// ```
/// use moonseed::{*, convenience::*};
/// let mut rt = Runtime::builder().wait_function("read", NativePolicy::VmLocal, "read.asset").build()?;
/// let read = rt.globals().raw_get::<_, Function>(&mut rt, "read")?;
/// let CallOutcome::Waiting(key) = rt.call::<i64>(&read, "answer", &mut Journal::new(), 1000)? else { return Err(ApiError::NotWaiting.into()) };
/// let outcome = complete_call::<i64>(&mut rt, key, Completion::Return(vec![Value::Integer(42)]), &mut Journal::new(), 1000)?;
/// assert!(matches!(outcome, CallOutcome::Done(42)));
/// # Ok::<(), EmbedError>(())
/// ```
///
/// The construction methods compose into one runtime:
/// ```
/// # use moonseed::*;
/// struct Counter;
/// impl HostUserdata for Counter { const SYMBOL: &'static str = "app.Counter"; fn logical_size(&self) -> u64 { 0 } }
/// let mut rt = Runtime::builder().expose("double", NativePolicy::VmLocal, |_, n: i64| Ok(n * 2))
/// .userdata::<Counter>()?.wait_function("read", NativePolicy::VmLocal, "read.asset").build()?;
/// let counter = rt.create_host_userdata(Counter, 0)?;
/// rt.globals().raw_set(&mut rt, "counter", counter)?;
/// # Ok::<(), Error>(())
/// ```
pub fn wait_function(
mut self,
name: impl Into<String>,
policy: crate::NativePolicy,
operation: impl Into<String>,
) -> Self {
let name = name.into();
let operation = operation.into();
self.registry.function(name.clone(), policy, move |cx| {
Ok(crate::NativeReturn::Wait(crate::WaitRequest {
operation: operation.clone(),
payload: cx.arguments::<crate::MultiValue>()?,
}))
});
self.publish_on_build(name);
self
}
/// Choose native panic handling. Defaults to [`NativePanicPolicy::Poison`].
/// Recovery converts an unwinding panic into an ordinary Lua error, so
/// protected calls and shutdown finalizers can run; it rolls back no effects.
pub fn native_panic_policy(mut self, policy: NativePanicPolicy) -> Self {
self.native_panic_policy = policy;
self
}
/// Choose how resource memory errors affect execution. The default is
/// catchable; terminal errors return `StepOutcome::Terminated(MemoryLimit)`
/// without unwinding or running Lua close handlers. Further runs remain
/// terminated, and loading or starting another call is refused.
pub fn memory_error_policy(mut self, policy: MemoryErrorPolicy) -> Self {
self.memory_error_policy = policy;
self
}
/// Set initial byte-string package paths. Paths grant no filesystem authority.
/// Dynamic C loading is unsupported; cpath is exposed only as configuration.
pub fn package_paths(mut self, path: impl AsRef<[u8]>, cpath: impl AsRef<[u8]>) -> Self {
self.package_path = path.as_ref().to_vec();
self.package_cpath = cpath.as_ref().to_vec();
self
}
/// Supply independent filesystem authority.
pub fn filesystem(mut self, capability: std::sync::Arc<dyn crate::Filesystem>) -> Self {
self.capabilities = self.capabilities.filesystem(capability);
self
}
/// Supply independent stdio authority.
pub fn stdio(mut self, capability: std::sync::Arc<dyn crate::Stdio>) -> Self {
self.capabilities = self.capabilities.stdio(capability);
self
}
/// Supply independent clock authority.
pub fn clock(mut self, capability: std::sync::Arc<dyn crate::Clock>) -> Self {
self.capabilities = self.capabilities.clock(capability);
self
}
/// Supply independent civil authority.
pub fn civil(mut self, capability: std::sync::Arc<dyn crate::CivilTime>) -> Self {
self.capabilities = self.capabilities.civil(capability);
self
}
/// Supply independent environment authority.
pub fn environment(mut self, capability: std::sync::Arc<dyn crate::Environment>) -> Self {
self.capabilities = self.capabilities.environment(capability);
self
}
/// Supply independent process authority.
pub fn process(mut self, capability: std::sync::Arc<dyn crate::Process>) -> Self {
self.capabilities = self.capabilities.process(capability);
self
}
/// Replace configuration, including any previously supplied limits.
pub fn config(mut self, config: Config) -> Self {
self.config = config;
self
}
/// Replace resource limits in the current configuration.
pub fn limits(mut self, limits: Limits) -> Self {
self.config.max_objects = limits.max_objects;
self.config.max_logical_heap = limits.max_logical_heap;
self.config.max_stack_slots = limits.max_stack_slots;
self.config.max_string_bytes = limits.max_string_bytes;
self.config.max_snapshot_bytes = limits.max_snapshot_bytes;
self
}
/// Install a host registry. Selected libraries register their own symbols.
pub fn registry(mut self, registry: HostRegistry) -> Self {
self.registry = registry;
self
}
/// Select libraries to register and install together. No library grants host
/// IO or OS authority; attach [`super::HostCapabilities`] separately.
/// Restore automatically supplies library symbols; restrict the restoring
/// host with [`super::Host::libraries`] when accepting untrusted snapshots.
pub fn libraries(mut self, libraries: Libraries) -> Self {
self.libraries = libraries;
self
}
/// Set the output sink used by `print`.
pub fn output(mut self, output: impl FnMut(&[u8]) + 'static) -> Self {
self.capabilities = self.capabilities.output(output);
self
}
/// Set the warnings sink, including Lua's continuation flag.
pub fn warnings(mut self, warnings: impl FnMut(&[u8], bool) + 'static) -> Self {
self.capabilities = self.capabilities.warnings(warnings);
self
}
/// Set the entropy source used by unseeded `math.randomseed`.
pub fn entropy(mut self, entropy: impl FnMut() -> i64 + 'static) -> Self {
self.capabilities = self.capabilities.entropy(entropy);
self
}
/// Replace all optional host capabilities together.
pub fn capabilities(mut self, capabilities: super::HostCapabilities) -> Self {
self.capabilities = capabilities;
self
}
/// Supply resources used to rebind userdata on restore.
pub fn host_env(mut self, env: super::HostEnv) -> Self {
self.capabilities = self.capabilities.host_env(env);
self
}
/// Install a host module searcher after the preload searcher.
pub fn module_resolver(
mut self,
policy: super::ResolverPolicy,
resolver: impl super::ModuleResolver,
) -> Self {
self.capabilities = self.capabilities.module_resolver(policy, resolver);
self
}
/// Build an idle runtime with an existing main thread. Resource failure
/// is a Lua error; before a runtime exists its error value is nil.
///
/// # Errors
///
/// Returns a Lua memory/stack error if construction, library installation
/// or publishing exposed callbacks exceeds limits; terminal memory policy
/// returns a VM memory error instead. Missing exposed symbols and other
/// initialization failures retain their API or VM error categories.
pub fn build(mut self) -> Result<Runtime> {
let exposed = std::mem::take(&mut self.exposed);
let mut runtime = Runtime::api_build(self)?;
for name in exposed {
let function = runtime.make_closure(&name, ())?;
runtime
.globals()
.raw_set(&mut runtime, name.as_bytes(), function)?;
}
Ok(runtime)
}
}