moonseed 0.2.0

Deterministic, checkpointable Lua 5.4 runtime in safe Rust
Documentation
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
use super::{
    AnyUserData, ApiError, FromLua, FromLuaMulti, Function, IntoLua, IntoLuaMulti, LuaError,
    LuaString, MultiValue, Result, Table, UserDataRefMut, Value, ValueRef,
};
use crate::value::Value as Raw;
use crate::{EffectId, HostUserdata, Journal, Runtime, WaitKey};

pub(crate) type TypedCallback = dyn Fn(&mut NativeContext<'_>) -> Result<()>;

pub(crate) type Callback = dyn Fn(&mut NativeContext<'_>) -> Result<NativeReturn>;

/// A native's results or its next execution request. Calls never recurse
/// into the executor: Lua runs after the callback and its borrows end.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum NativeReturn {
    /// Return an exact sequence, including nil holes.
    Return(MultiValue),
    /// Raise an arbitrary Lua error object.
    Error(Value),
    /// Suspend until the host completes the VM-issued key.
    Wait(WaitRequest),
    /// Call a callable Lua value and resume this symbol in a new VM step.
    /// Yields may cross this frame whenever the containing thread may yield.
    CallLua {
        /// A function or a value with `__call`.
        function: Value,
        /// The call's arguments.
        args: MultiValue,
        /// An application-defined continuation discriminator.
        tag: u32,
        /// Values kept alive until the continuation resumes.
        keep: MultiValue,
    },
    /// Call a Lua value behind a non-yielding C-call boundary.
    ///
    /// The calling thread reports `coroutine.isyieldable() == false` until
    /// this call returns. Attempts to yield across it raise Lua's catchable
    /// `attempt to yield across a C-call boundary` error in a coroutine, or
    /// `attempt to yield from outside a coroutine` on the main thread.
    /// Child coroutines may still yield to their resumers. Host waits and fuel
    /// pauses remain allowed, and the boundary survives snapshots taken at
    /// either pause.
    /// Nested `CallLua` calls cannot relax this restriction. Results, errors,
    /// continuation tags and kept values behave exactly as for [`Self::CallLua`].
    CallLuaNoYield {
        /// A function or a value with `__call`.
        function: Value,
        /// The call's arguments.
        args: MultiValue,
        /// An application-defined continuation discriminator.
        tag: u32,
        /// Values kept alive until the continuation resumes.
        keep: MultiValue,
    },
}

impl From<MultiValue> for NativeReturn {
    fn from(values: MultiValue) -> Self {
        Self::Return(values)
    }
}

/// A host operation's name and exact Lua payload.
#[derive(Clone, Debug)]
pub struct WaitRequest {
    /// Stable operation name, preserved in snapshots.
    pub operation: String,
    /// Values the host can inspect through `Runtime::wait`.
    pub payload: MultiValue,
}

/// The pending operation associated with a wait key.
pub type WaitInfo = WaitRequest;

/// How a native's own Lua call ended.
#[derive(Clone, Debug)]
pub enum ResumeOutcome {
    /// The call returned these exact values.
    Returned(MultiValue),
    /// The frame caught the call's Lua error.
    Errored(LuaError),
}

/// Snapshot-backed continuation state supplied on reinvocation.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Resume {
    /// The tag supplied by `CallLua`.
    pub tag: u32,
    /// The called function's return or error.
    pub outcome: ResumeOutcome,
    /// The values retained by `CallLua`.
    pub kept: MultiValue,
}

/// How the host ends a wait. Object values are owner checked.
#[derive(Clone, Debug)]
pub enum Completion {
    /// Return the exact values.
    Return(Vec<Value>),
    /// Raise this unchanged Lua error object.
    Error(Value),
}

/// The result of driving a main-thread call with a fuel bound.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum CallOutcome<R> {
    /// The call completed and converted its results.
    Done(R),
    /// The call is waiting for this host operation.
    Waiting(WaitKey),
    /// Lua requested exit; the runtime is terminal.
    ExitRequested {
        /// The requested status.
        status: crate::ExitStatus,
        /// Whether runtime closing completed before returning.
        close: bool,
    },
    /// The fuel bound ended; continue with `run` and `finish_call`.
    OutOfFuel,
}

/// One callback invocation. Borrowed arguments add no roots. Mutable
/// userdata borrows hold the context, so they cannot cross a Lua call.
///
/// ```compile_fail,E0502
/// use moonseed::{NativeContext, NativeReturn, AnyUserData, HostUserdata, MultiValue};
/// struct Counter(i64);
/// impl HostUserdata for Counter {
///     const SYMBOL: &'static str = "doctest.Counter";
///     fn logical_size(&self) -> u64 { 8 }
/// }
/// fn held(cx: &mut NativeContext<'_>) -> moonseed::Result<NativeReturn> {
///     let object: AnyUserData = cx.argument(0)?;
///     let mut guard = cx.borrow_userdata_mut::<Counter>(&object)?;
///     let call = NativeReturn::CallLua {
///         function: cx.arg(1).to_owned_value()?,
///         args: MultiValue::new(), tag: 0, keep: MultiValue::new(),
///     };
///     guard.0 += 1;
///     Ok(call)
/// }
/// ```
pub struct NativeContext<'cx> {
    pub(crate) runtime: &'cx mut Runtime,
    pub(crate) args: &'cx [Raw],
    pub(crate) callee: Raw,
    pub(crate) effect: Option<EffectId>,
    pub(crate) journal: Option<&'cx mut Journal>,
    pub(crate) resume: Option<&'cx Resume>,
}

impl NativeContext<'_> {
    /// Charge fuel before performing bounded host work (for example, per byte).
    /// Charges count toward both total fuel and the current run quantum. A
    /// callback is atomic: quantum exhaustion pauses at its next VM boundary,
    /// so the host must bound each callback independently. Exceeding the hard
    /// fuel limit terminates the runtime even if the callback catches the error.
    /// With no configured limit, the representable total (`u64::MAX`) is the
    /// limit: charges beyond it terminate with `FuelLimitExceeded`, without
    /// wrapping. A charge that exactly reaches a limit succeeds; the next
    /// positive charge or fueled VM step terminates.
    /// Zero units is a no-op. This does not allocate or create a GC safe point.
    ///
    /// # Errors
    ///
    /// Returns `Error::Vm(VmError::FuelLimitExceeded)` when the total
    /// fuel bound would be exceeded; this also terminates the runtime.
    pub fn charge_fuel(&mut self, units: u64) -> Result<()> {
        self.runtime.api_charge_fuel(units)
    }

    /// The argument count, including nil holes.
    pub fn arg_count(&self) -> usize {
        self.args.len()
    }
    /// Borrow argument `index` (zero-based), or nil when absent.
    #[inline]
    pub fn arg(&self, index: usize) -> ValueRef<'_> {
        ValueRef::new(
            self.runtime,
            self.args.get(index).copied().unwrap_or(Raw::Nil),
        )
    }
    /// Borrow a string argument's exact bytes, without rooting or coercion.
    pub fn string_bytes(&self, index: usize) -> Option<&[u8]> {
        self.arg(index).as_string().map(|string| string.as_bytes())
    }
    /// Extract a typed argument, positioning failures one-based.
    /// If the one-based index cannot fit in `usize`, the failure is unpositioned.
    #[inline]
    ///
    /// # Errors
    ///
    /// Returns the requested type conversion error with a one-based argument
    /// position where representable, or an error from the conversion implementation.
    ///
    /// # Panics
    ///
    /// Propagates panics from user-supplied conversion implementations.
    pub fn argument<T: FromLua>(&mut self, index: usize) -> Result<T> {
        <T as FromLua>::from_context(self, index)
            .map_err(|error| positioned(error, index.checked_add(1)))
    }
    /// Extract the invocation's arguments as a typed sequence.
    #[inline]
    ///
    /// # Errors
    ///
    /// Returns argument conversion errors or errors from the
    /// `FromLuaMulti` implementation.
    ///
    /// # Panics
    ///
    /// Propagates panics from user-supplied conversion implementations.
    pub fn arguments<A: FromLuaMulti>(&mut self) -> Result<A> {
        <A as FromLuaMulti>::from_context(self)
    }
    /// Turn a positioned conversion failure into a catchable Lua argument error.
    /// Use this when converting arguments in a `HostRegistry::function` callback.
    pub fn argument_error(&mut self, error: super::Error) -> super::Error {
        self.runtime.api_argument_error(self.callee, error)
    }
    /// Prepare a custom Lua argument error; indexes are zero-based.
    ///
    /// # Errors
    ///
    /// Returns resource errors if the diagnostic string cannot be allocated,
    /// or a VM/root error for invalid current call state.
    pub fn bad_argument(&mut self, index: usize, detail: &str) -> Result<super::LuaError> {
        self.runtime.api_bad_argument(index, detail.as_bytes())
    }
    #[inline]
    pub(crate) fn write_results<R: IntoLuaMulti>(&mut self, values: R) -> Result<()> {
        values.write_native(self)
    }
    #[inline]
    pub(crate) fn push_result(&mut self, value: Value) -> Result<()> {
        let raw = value.raw(self.runtime)?;
        self.runtime.native_results.push(raw);
        Ok(())
    }
    pub(crate) fn take_results(&mut self) -> Result<MultiValue> {
        let raw = std::mem::take(&mut self.runtime.native_results);
        raw.iter()
            .map(|value| self.runtime.api_owned(*value))
            .collect::<Result<Vec<_>>>()
            .map(MultiValue)
    }
    /// Borrow all native closure captures, in slot order.
    pub fn captures(&self) -> Vec<ValueRef<'_>> {
        self.runtime
            .api_captures(self.callee)
            .iter()
            .map(|raw| ValueRef::new(self.runtime, *raw))
            .collect()
    }
    /// Replace a zero-based capture using the collector's write barrier.
    ///
    /// # Errors
    ///
    /// Returns conversion/ownership errors for `value`, or
    /// `ApiError::InvalidCallState` for a missing closure capture slot.
    ///
    /// # Panics
    ///
    /// Propagates panics from user-supplied conversion implementations.
    pub fn set_capture<V: IntoLua>(&mut self, index: usize, value: V) -> Result<()> {
        let value = value.into_lua(self.runtime)?;
        self.runtime.api_set_capture(self.callee, index, &value)
    }
    /// An owned copy of the continuation supplied when the native's Lua call ends.
    /// Use [`Self::resumed_ref`] to inspect it without copying its value buffers.
    pub fn resumed(&self) -> Option<Resume> {
        self.resume.cloned()
    }
    /// Borrow the continuation without copying its kept or returned values.
    pub fn resumed_ref(&self) -> Option<&Resume> {
        self.resume
    }
    /// Request a Lua call using reusable argument and continuation buffers.
    ///
    /// # Errors
    ///
    /// Returns conversion/ownership/resource errors while converting the
    /// function, arguments or kept values. Lua call failures arrive later through
    /// the continuation; this method does not execute the requested function.
    ///
    /// # Panics
    ///
    /// Propagates panics from user-supplied conversion implementations.
    pub fn call_lua(
        &mut self,
        function: impl IntoLua,
        args: impl IntoLuaMulti,
        tag: u32,
        keep: impl IntoLuaMulti,
    ) -> Result<NativeReturn> {
        Ok(NativeReturn::CallLua {
            function: function.into_lua(self.runtime)?,
            args: args.into_lua_multi(self.runtime)?,
            tag,
            keep: keep.into_lua_multi(self.runtime)?,
        })
    }
    /// Convert any result sequence into a native return.
    #[inline]
    ///
    /// # Errors
    ///
    /// Returns conversion/ownership/resource errors from `IntoLuaMulti`.
    ///
    /// # Panics
    ///
    /// Propagates panics from user-supplied conversion implementations.
    pub fn return_values<R: IntoLuaMulti>(&mut self, values: R) -> Result<NativeReturn> {
        values
            .into_lua_multi(self.runtime)
            .map(NativeReturn::Return)
    }
    /// Create a rooted byte string.
    ///
    /// # Errors
    ///
    /// Returns the quota and VM errors from [`Runtime::create_string`].
    pub fn create_string(&mut self, bytes: impl AsRef<[u8]>) -> Result<LuaString> {
        self.runtime.create_string(bytes)
    }
    /// Create a rooted empty table.
    ///
    /// # Errors
    ///
    /// Returns the quota and VM errors from [`Runtime::create_table`].
    pub fn create_table(&mut self) -> Result<Table> {
        self.runtime.create_table()
    }
    /// Create registered host userdata.
    ///
    /// # Errors
    ///
    /// Returns the registration, quota and VM errors from
    /// [`Runtime::create_host_userdata`].
    ///
    /// # Panics
    ///
    /// Propagates a panic from the payload's `logical_size` implementation.
    pub fn create_userdata<T: HostUserdata>(
        &mut self,
        value: T,
        user_values: usize,
    ) -> Result<AnyUserData> {
        self.runtime.create_host_userdata(value, user_values)
    }
    /// Create a native closure with at most 255 captures.
    ///
    /// # Errors
    ///
    /// Returns unknown-symbol, capture-count, conversion, ownership or
    /// resource errors from [`Runtime::make_closure`].
    ///
    /// # Panics
    ///
    /// Propagates panics from user-supplied conversion implementations.
    pub fn make_closure(&mut self, symbol: &str, captures: impl IntoLuaMulti) -> Result<Function> {
        self.runtime.make_closure(symbol, captures)
    }
    /// Borrow a typed host userdata payload.
    ///
    /// # Errors
    ///
    /// Returns ownership/released-root errors, or `ApiError::WrongType`
    /// when the userdata does not contain `T`.
    pub fn borrow_userdata<'a, T: HostUserdata>(&'a self, value: &AnyUserData) -> Result<&'a T> {
        value.borrow(self.runtime)
    }
    /// Borrow a typed mutable payload, holding the context until dropped.
    ///
    /// # Errors
    ///
    /// Returns ownership/released-root errors, or `ApiError::WrongType`
    /// when the userdata does not contain `T`.
    pub fn borrow_userdata_mut<'a, T: HostUserdata>(
        &'a mut self,
        value: &AnyUserData,
    ) -> Result<UserDataRefMut<'a, T>> {
        value.borrow_mut(self.runtime)
    }
    /// Read a raw table entry without running Lua.
    /// Read a table without running `__index`. Ownership and conversion errors
    /// are [`ApiError`]s. For semantic indexing, pass a Lua accessor
    /// (`function(t, k) return t[k] end`) to [`Self::call_lua`] and handle
    /// [`ResumeOutcome`] on reinvocation. No Rust borrow crosses that call;
    /// its arguments/kept values and continuation are checkpoint state.
    ///
    /// # Errors
    ///
    /// Returns table/key ownership errors, conversion errors for the key or
    /// result, or VM errors for invalid table state. No metamethod is invoked.
    ///
    /// # Panics
    ///
    /// Propagates panics from user-supplied conversion implementations.
    pub fn raw_get<K: IntoLua, V: FromLua>(&mut self, table: &Table, key: K) -> Result<V> {
        table.raw_get(self.runtime, key)
    }
    /// Borrow any owned value in this callback, checking runtime ownership.
    /// In particular this exposes raw string-key/value bytes returned by
    /// [`Self::raw_pairs`] without copying or requiring a Runtime borrow.
    ///
    /// # Errors
    ///
    /// Returns ownership/released-root errors for a value that cannot be
    /// borrowed in this runtime.
    pub fn value_ref(&self, value: &Value) -> Result<ValueRef<'_>> {
        value.as_ref(self.runtime)
    }
    /// Start bounded raw traversal usable inside a native callback.
    /// Root depth is 0; increase depth for children and share one
    /// [`super::TraversalBudget`] across the entire conversion.
    ///
    /// # Errors
    ///
    /// Returns ownership, released-root or wrong-type errors for the table.
    /// The traversal cursor checks its visit/depth/fuel budgets when advanced.
    pub fn raw_pairs(&mut self, table: &Table, depth: usize) -> Result<super::TableTraversal> {
        self.runtime.api_traversal(table, depth)
    }
    /// Write a raw table entry without running Lua.
    ///
    /// # Errors
    ///
    /// Returns ownership/conversion errors, `ApiError::InvalidKey` for nil
    /// or NaN keys, or resource/VM errors when growing the table.
    ///
    /// # Panics
    ///
    /// Propagates panics from user-supplied conversion implementations.
    pub fn raw_set<K: IntoLua, V: IntoLua>(
        &mut self,
        table: &Table,
        key: K,
        value: V,
    ) -> Result<()> {
        table.raw_set(self.runtime, key, value)
    }
    /// Read the raw table border.
    ///
    /// # Errors
    ///
    /// Returns ownership/released-root or wrong-type errors for the table.
    pub fn raw_len(&self, table: &Table) -> Result<i64> {
        table.raw_len(self.runtime)
    }
    /// Read a value's actual metatable, bypassing protection.
    ///
    /// # Errors
    ///
    /// Returns object conversion/ownership errors or VM/root errors while
    /// rooting its actual metatable.
    ///
    /// # Panics
    ///
    /// Propagates panics from user-supplied conversion implementations.
    pub fn metatable<V: IntoLua>(&mut self, object: V) -> Result<Option<Table>> {
        let object = object.into_lua(self.runtime)?;
        self.runtime.api_value_metatable(&object)
    }
    /// Set or clear a table's or userdata's actual metatable.
    ///
    /// # Errors
    ///
    /// Returns conversion/ownership errors, including a foreign metatable,
    /// or `ApiError::WrongType` unless the object is a table or userdata.
    ///
    /// # Panics
    ///
    /// Propagates panics from user-supplied conversion implementations.
    pub fn set_metatable<V: IntoLua>(&mut self, object: V, meta: Option<&Table>) -> Result<()> {
        let object = object.into_lua(self.runtime)?;
        self.runtime.api_value_set_metatable(&object, meta)
    }
    /// Effect identity, available only to external natives.
    pub fn effect(&self) -> Option<EffectId> {
        self.effect
    }
    /// Journal, available only to external natives.
    pub fn journal(&mut self) -> Option<&mut Journal> {
        self.journal.as_deref_mut()
    }
}

fn positioned(error: super::Error, index: Option<usize>) -> super::Error {
    if let super::Error::Api(ApiError::Conversion(mut error)) = error {
        error.position = index;
        error.into()
    } else {
        error
    }
}

impl NativeContext<'_> {
    /// Root the thread executing this native.
    ///
    /// # Errors
    ///
    /// Returns a VM/root error if the active thread is absent or invalid.
    pub fn current_thread(&mut self) -> Result<Value> {
        let thread = self.runtime.heap().active.ok_or(crate::VmError::Corrupt)?;
        self.runtime.api_owned(Raw::Thread(thread))
    }
    /// Root the globals table.
    pub fn globals(&mut self) -> Table {
        self.runtime.globals()
    }
    /// Install a hook; no thread selects the currently executing thread.
    ///
    /// # Errors
    ///
    /// Returns invalid-thread/ownership errors, an unknown hook symbol,
    /// or resource/VM errors when installing the hook.
    pub fn set_hook(
        &mut self,
        thread: Option<&Value>,
        symbol: &str,
        mask: super::HookMask,
        count: i32,
    ) -> Result<()> {
        let current = self.current_thread()?;
        self.runtime
            .set_hook(Some(thread.unwrap_or(&current)), symbol, mask, count)
    }
    /// Remove a hook; no thread selects the currently executing thread.
    ///
    /// # Errors
    ///
    /// Returns invalid-thread/ownership errors or a VM/root error when
    /// the selected thread cannot be accessed.
    pub fn clear_hook(&mut self, thread: Option<&Value>) -> Result<()> {
        let current = self.current_thread()?;
        self.runtime.clear_hook(Some(thread.unwrap_or(&current)))
    }
    /// Inspect a hook; no thread selects the currently executing thread.
    ///
    /// # Errors
    ///
    /// Returns invalid-thread/ownership errors or a VM/root error when
    /// the selected thread cannot be accessed.
    pub fn get_hook(&mut self, thread: Option<&Value>) -> Result<Option<super::HookSettings>> {
        let current = self.current_thread()?;
        self.runtime.get_hook(Some(thread.unwrap_or(&current)))
    }
}