Skip to main content

moonseed/
host.rs

1//! Host functions are registry symbols, not serialized pointers.
2//!
3//! Two kinds exist. The legacy `HostFn` (one integer in, one out) is what
4//! the proof kernel's `CallHost` instruction calls. A native function
5//! ([`NativeFn`]) is an ordinary Lua value, called with `Call`, with any
6//! number of arguments and results and a declared [`NativePolicy`].
7//!
8//! The journal is embedder state. Moonseed stores only the next sequence
9//! number and the pending call. Replaying an [`EffectId`] must return the
10//! outcome already stored in the journal.
11
12use crate::heap::Heap;
13use crate::id::WaitKey;
14use crate::value::Value;
15
16/// Host-owned lineage. Exact restore keeps it; a future fork would mint a new one.
17#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
18pub struct EffectId {
19    /// The host-selected journal lineage.
20    pub domain: u64,
21    /// The deterministic effect number within that lineage.
22    pub sequence: u64,
23}
24
25/// One persisted journal outcome and its request identity.
26#[derive(Clone, PartialEq, Eq, Debug)]
27pub struct EffectRecord {
28    /// The effect identity.
29    pub id: EffectId,
30    /// The integer request metadata.
31    pub arg: i64,
32    /// Integer outcome; byte effects use `bytes` and leave this zero.
33    pub outcome: i64,
34    /// Byte outcome for byte effects; integer effects leave this unset.
35    pub bytes: Option<Vec<u8>>,
36    /// Exact general capability request identity (versioned bytes).
37    pub request: Option<Vec<u8>>,
38    /// Exact request bytes for a named module effect (legacy compatible).
39    pub module: Option<Vec<u8>>,
40}
41
42/// A journal payload mismatch. No callback is repeated on a mismatch.
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub struct JournalError;
45
46impl std::fmt::Display for JournalError {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        f.write_str("journal payload mismatch")
49    }
50}
51impl std::error::Error for JournalError {}
52
53mod journal_payload {
54    pub trait Sealed {}
55    impl Sealed for i64 {}
56    impl Sealed for Vec<u8> {}
57}
58
59/// Payloads accepted by [`Journal::commit`]: integers and byte vectors.
60/// Both forms fail on a payload kind mismatch without repeating the callback.
61pub trait JournalPayload: journal_payload::Sealed + Sized {
62    /// Create the stored record for this payload kind.
63    #[doc(hidden)]
64    fn record(self, id: EffectId, arg: i64) -> EffectRecord;
65    /// Read a matching outcome, refusing a different payload kind.
66    #[doc(hidden)]
67    fn replay(record: &EffectRecord) -> Result<Self, JournalError>;
68}
69
70impl JournalPayload for i64 {
71    fn record(self, id: EffectId, arg: i64) -> EffectRecord {
72        EffectRecord {
73            id,
74            arg,
75            outcome: self,
76            bytes: None,
77            module: None,
78            request: None,
79        }
80    }
81    fn replay(record: &EffectRecord) -> Result<Self, JournalError> {
82        if record.bytes.is_none() {
83            Ok(record.outcome)
84        } else {
85            Err(JournalError)
86        }
87    }
88}
89
90impl JournalPayload for Vec<u8> {
91    fn record(self, id: EffectId, arg: i64) -> EffectRecord {
92        EffectRecord {
93            id,
94            arg,
95            outcome: 0,
96            bytes: Some(self),
97            module: None,
98            request: None,
99        }
100    }
101    fn replay(record: &EffectRecord) -> Result<Self, JournalError> {
102        record.bytes.clone().ok_or(JournalError)
103    }
104}
105
106/// Map from effect id to the outcome that was committed.
107///
108/// A duplicate id returns the stored outcome and does not run `fresh` again.
109#[derive(Clone, Debug, Default)]
110pub struct Journal {
111    entries: Vec<EffectRecord>,
112    /// Position of each id in `entries`, so a commit is not a linear scan.
113    index: std::collections::HashMap<EffectId, usize>,
114}
115
116impl PartialEq for Journal {
117    fn eq(&self, other: &Self) -> bool {
118        self.entries == other.entries
119    }
120}
121
122impl Eq for Journal {}
123
124impl Journal {
125    /// Create an empty effect journal.
126    pub fn new() -> Self {
127        Self::default()
128    }
129
130    /// Borrow journal outcomes in their insertion order.
131    pub fn entries(&self) -> &[EffectRecord] {
132        &self.entries
133    }
134
135    /// Commit integer or byte outcomes exactly once per effect id.
136    pub fn commit<P: JournalPayload>(
137        &mut self,
138        id: EffectId,
139        arg: i64,
140        fresh: impl FnOnce() -> P,
141    ) -> Result<P, JournalError> {
142        if let Some(&position) = self.index.get(&id) {
143            // Legacy callers have no exact request to verify. They cannot
144            // consume a record belonging to a different capability operation.
145            if self.entries[position].request.is_some() {
146                return Err(JournalError);
147            }
148            return P::replay(&self.entries[position]);
149        }
150        let record = fresh().record(id, arg);
151        let outcome = P::replay(&record);
152        self.index.insert(id, self.entries.len());
153        self.entries.push(record);
154        outcome
155    }
156
157    /// Insert a record without running a host. Used to simulate a torn journal.
158    pub fn seed(&mut self, id: EffectId, arg: i64, outcome: i64) {
159        let _ = self.seed_record(outcome.record(id, arg));
160    }
161
162    /// Reconstruct an integer or byte record persisted by the host, including
163    /// its module or capability request. Duplicate ids keep the previously stored outcome.
164    pub fn seed_record(&mut self, record: EffectRecord) -> Result<(), JournalError> {
165        if record.bytes.is_some() && record.outcome != 0
166            || record.module.is_some() && record.bytes.is_none()
167            || record.module.is_some() && record.request.is_some()
168        {
169            return Err(JournalError);
170        }
171        if !self.index.contains_key(&record.id) {
172            self.index.insert(record.id, self.entries.len());
173            self.entries.push(record);
174        }
175        Ok(())
176    }
177
178    /// Replay an exact request or report a mismatch without invoking any host.
179    /// Legacy records with no request remain valid only for legacy `commit`.
180    pub fn replay_request<P: JournalPayload>(
181        &self,
182        id: EffectId,
183        arg: i64,
184        request: &[u8],
185    ) -> Result<Option<P>, JournalError> {
186        let Some(&position) = self.index.get(&id) else {
187            return Ok(None);
188        };
189        let record = &self.entries[position];
190        if record.arg != arg
191            || record.module.is_some()
192            || record.request.as_deref() != Some(request)
193        {
194            return Err(JournalError);
195        }
196        P::replay(record).map(Some)
197    }
198
199    /// Commit an outcome with exact request verification on replay, for reads
200    /// and mutations alike. A mismatch never invokes `fresh` or rewrites a record.
201    pub fn commit_request<P: JournalPayload>(
202        &mut self,
203        id: EffectId,
204        arg: i64,
205        request: &[u8],
206        fresh: impl FnOnce() -> P,
207    ) -> Result<P, JournalError> {
208        if let Some(outcome) = self.replay_request(id, arg, request)? {
209            return Ok(outcome);
210        }
211        let mut record = fresh().record(id, arg);
212        record.request = Some(request.to_vec());
213        let outcome = P::replay(&record);
214        self.index.insert(id, self.entries.len());
215        self.entries.push(record);
216        outcome
217    }
218
219    pub(crate) fn module_result(&self, domain: u64, name: &[u8]) -> Option<(EffectId, &[u8])> {
220        self.entries.iter().find_map(|record| {
221            (record.id.domain == domain && record.module.as_deref() == Some(name))
222                .then(|| record.bytes.as_deref().map(|bytes| (record.id, bytes)))?
223        })
224    }
225
226    pub(crate) fn commit_module(
227        &mut self,
228        id: EffectId,
229        name: &[u8],
230        fresh: impl FnOnce() -> Vec<u8>,
231    ) -> Result<Vec<u8>, JournalError> {
232        if let Some(&position) = self.index.get(&id)
233            && (self.entries[position].module.as_deref() != Some(name)
234                || self.entries[position].request.is_some())
235        {
236            return Err(JournalError);
237        }
238        let outcome = self.commit(id, 0, fresh)?;
239        let position = self.index[&id];
240        let record = &mut self.entries[position];
241        record.module = Some(name.to_vec());
242        Ok(outcome)
243    }
244}
245
246pub struct HostCtx<'a> {
247    pub journal: &'a mut Journal,
248    pub effect: EffectId,
249}
250
251pub enum HostResult {
252    Ready(i64),
253    Pending(WaitKey),
254    /// The legacy proof host rejected an incompatible journal record.
255    Fault,
256}
257
258#[deprecated(note = "use HostRegistry::function or HostRegistry::typed")]
259pub type HostFn = fn(&mut HostCtx<'_>, i64) -> HostResult;
260
261/// How a native function relates to state outside the VM.
262#[derive(Clone, Copy, PartialEq, Eq, Debug)]
263pub enum NativePolicy {
264    /// Reads its arguments and returns values. Anything it changes is VM
265    /// state, which a checkpoint already restores. No effect id, no journal.
266    VmLocal,
267    /// Acts on the world outside the VM. Each call gets an [`EffectId`] and
268    /// stops at a prepared safe point before it runs; the function commits
269    /// through the journal, so a replayed id returns the stored outcome.
270    External,
271}
272
273/// What a native function asks the VM to do after it returns.
274#[derive(Clone, Copy, PartialEq, Eq, Debug)]
275pub enum NativeOutcome {
276    /// The pushed results are the call's results.
277    Ready,
278    /// The caller waits until [`crate::Runtime::complete_wait`] with this key.
279    Pending(WaitKey),
280    /// The call raises `LuaFault::Native`.
281    Fault,
282}
283
284/// A native function. It must not call back into Lua.
285pub type NativeFn = fn(&mut NativeCall<'_>) -> NativeOutcome;
286
287/// The Lua type of a value, as `type()` names it.
288#[derive(Clone, Copy, PartialEq, Eq, Debug)]
289pub enum LuaType {
290    /// Lua nil.
291    Nil,
292    /// Lua boolean.
293    Boolean,
294    /// Lua integer or floating-point number.
295    Number,
296    /// Lua byte string.
297    String,
298    /// Lua table.
299    Table,
300    /// Lua callable function.
301    Function,
302    /// Lua coroutine.
303    Thread,
304    /// Full or light: `type()` names both `userdata`.
305    /// `NativeCall::light` tells them apart.
306    Userdata,
307}
308
309/// A Lua value inside one native call. It cannot outlive the call: the
310/// lifetime ties it to the [`NativeCall`] it came from, and no collection
311/// runs while a native function runs.
312#[derive(Clone, Copy)]
313pub struct NativeValue<'a> {
314    pub(crate) value: Value,
315    _call: std::marker::PhantomData<&'a ()>,
316}
317
318impl std::fmt::Debug for NativeValue<'_> {
319    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
320        let ty = match self.value {
321            Value::Nil => LuaType::Nil,
322            Value::Bool(_) => LuaType::Boolean,
323            Value::Integer(_) | Value::Float(_) => LuaType::Number,
324            Value::String(_) => LuaType::String,
325            Value::Table(_) => LuaType::Table,
326            Value::Closure(_) | Value::Native(_) | Value::NativeClosure(_) => LuaType::Function,
327            Value::Thread(_) => LuaType::Thread,
328            Value::Userdata(_) | Value::LightUserdata(..) => LuaType::Userdata,
329        };
330        f.debug_tuple("NativeValue").field(&ty).finish()
331    }
332}
333
334impl NativeValue<'_> {
335    pub(crate) fn wrap(value: Value) -> Self {
336        Self {
337            value,
338            _call: std::marker::PhantomData,
339        }
340    }
341}
342
343/// Why `NativeCall::raw_set` refused.
344#[derive(Clone, Copy, PartialEq, Eq, Debug)]
345pub enum RawSetError {
346    /// The target is not a table.
347    NotATable,
348    /// A nil or NaN key.
349    InvalidKey,
350    /// A new entry would pass the logical-heap quota. A native that returns
351    /// `NativeOutcome::Fault` after this raises a memory error.
352    Memory,
353}
354
355/// A Lua value as the host sees it or hands it in. Unstable API.
356///
357/// `Object` names a table, function, or thread that already exists in the
358/// runtime; `Native` names a registered native function by symbol.
359#[derive(Clone, Debug, PartialEq)]
360#[deprecated(note = "use Value and IntoLua/FromLua with rooted object values")]
361pub enum HostValue {
362    /// Lua nil.
363    Nil,
364    /// Lua boolean.
365    Boolean(bool),
366    /// Lua integer.
367    Integer(i64),
368    /// Lua integer or floating-point number.
369    Number(f64),
370    /// Lua byte string.
371    String(Vec<u8>),
372    /// An unrooted logical object identity.
373    Object(crate::id::ObjectId),
374    /// A registered native symbol.
375    Native(String),
376    /// A light userdata (ADR 0043). A full userdata is an `Object`.
377    LightUserdata(crate::userdata::LightUserdata),
378}
379
380/// Why a userdata operation of a [`NativeCall`] refused. Unstable API.
381#[derive(Clone, Copy, PartialEq, Eq, Debug)]
382pub enum UserdataError {
383    /// The value is not a full userdata of the kind asked for.
384    NotUserdata,
385    /// The host type is not registered with the runtime's registry.
386    Unregistered,
387    /// The logical-heap quota, or the payload or user-value bound, refused
388    /// it. A native that returns `NativeOutcome::Fault` after this raises
389    /// a memory error.
390    Memory,
391}
392
393/// How the host ends a native call that is waiting (`Runtime::complete`).
394/// Unstable API.
395#[derive(Clone, Debug, PartialEq)]
396#[deprecated(note = "use Completion with rooted Value objects")]
397pub enum LegacyCompletion {
398    /// The call returns these values.
399    Return(Vec<HostValue>),
400    /// The call raises this error object, as `error(value)` would.
401    Error(HostValue),
402}
403
404/// Arguments in, results out, for one native call. Unstable API.
405///
406/// Values that are not numbers, booleans, or nil can be passed through with
407/// `NativeCall::push_arg` but not inspected yet.
408#[deprecated(note = "use NativeContext with HostRegistry::function or typed")]
409pub type NativeCall<'a> = LegacyNativeCall<'a>;
410
411/// Diagnostics a legacy native records only when it returns `Fault`.
412pub(crate) enum NativeError {
413    Argument(usize, Vec<u8>),
414    Message(Vec<u8>, bool),
415}
416
417/// Compatibility storage for the deprecated function-pointer callbacks.
418#[doc(hidden)]
419pub struct LegacyNativeCall<'a> {
420    pub(crate) heap: &'a mut Heap,
421    pub(crate) args: &'a [Value],
422    pub(crate) results: &'a mut Vec<Value>,
423    pub(crate) effect: Option<EffectId>,
424    pub(crate) journal: Option<&'a mut Journal>,
425    /// A raw store was refused for the logical-heap quota; a `Fault` from
426    /// this call is then a memory error.
427    pub(crate) out_of_memory: bool,
428    /// The host userdata types the runtime knows (ADR 0044).
429    pub(crate) registry: &'a HostRegistry,
430    /// `Config::max_objects`: a userdata is refused past it, as every
431    /// other allocation is.
432    pub(crate) max_objects: u32,
433    /// An argument error [`NativeCall::type_error`] recorded: the
434    /// argument's index and the message. A `Fault` raises it.
435    pub(crate) error: Option<NativeError>,
436}
437
438impl<'a> LegacyNativeCall<'a> {
439    pub fn arg_count(&self) -> usize {
440        self.args.len()
441    }
442
443    /// Argument `index`, or nil past the end.
444    pub fn arg(&self, index: usize) -> NativeValue<'a> {
445        NativeValue::wrap(self.args.get(index).copied().unwrap_or(Value::Nil))
446    }
447
448    pub fn type_of(&self, value: NativeValue<'a>) -> LuaType {
449        match value.value {
450            Value::Nil => LuaType::Nil,
451            Value::Bool(_) => LuaType::Boolean,
452            Value::Integer(_) | Value::Float(_) => LuaType::Number,
453            Value::String(_) => LuaType::String,
454            Value::Table(_) => LuaType::Table,
455            Value::Closure(_) | Value::Native(_) | Value::NativeClosure(_) => LuaType::Function,
456            Value::Thread(_) => LuaType::Thread,
457            Value::Userdata(_) | Value::LightUserdata(..) => LuaType::Userdata,
458        }
459    }
460
461    /// A string's bytes, borrowed; any bytes, not only UTF-8.
462    pub fn string_bytes(&self, value: NativeValue<'a>) -> Option<&[u8]> {
463        match value.value {
464            Value::String(handle) => self.heap.string_bytes(handle),
465            _ => None,
466        }
467    }
468
469    /// `rawget(table, key)`. `None` if `table` is not a table. A nil or NaN
470    /// key reads nil.
471    pub fn raw_get(&self, table: NativeValue<'a>, key: NativeValue<'a>) -> Option<NativeValue<'a>> {
472        let Value::Table(handle) = table.value else {
473            return None;
474        };
475        let value = match self.heap.key_view(key.value) {
476            Ok(key) => self.heap.table_get_view(handle, key)?,
477            Err(_) => Value::Nil,
478        };
479        Some(NativeValue::wrap(value))
480    }
481
482    /// `rawset(table, key, value)`, with the ordinary key rules. Nil
483    /// deletes.
484    pub fn raw_set(
485        &mut self,
486        table: NativeValue<'a>,
487        key: NativeValue<'a>,
488        value: NativeValue<'a>,
489    ) -> Result<(), RawSetError> {
490        let Value::Table(handle) = table.value else {
491            return Err(RawSetError::NotATable);
492        };
493        if self.heap.update_string_key(handle, key.value, value.value) {
494            return Ok(());
495        }
496        let normalized = self
497            .heap
498            .normalize_value(key.value)
499            .map_err(|_| RawSetError::InvalidKey)?;
500        match self
501            .heap
502            .table_insert(handle, normalized, key.value, value.value)
503        {
504            Ok(()) => Ok(()),
505            Err(crate::heap::InsertError::NoTable) => Err(RawSetError::NotATable),
506            Err(crate::heap::InsertError::Memory) => {
507                self.out_of_memory = true;
508                Err(RawSetError::Memory)
509            }
510        }
511    }
512
513    /// `rawlen(value)`: a table's border or a string's byte length.
514    /// `a == b` without `__eq`: numbers by value, strings by bytes,
515    /// everything else by identity.
516    pub fn raw_equal(&self, a: NativeValue<'a>, b: NativeValue<'a>) -> bool {
517        crate::compare::equal(self.heap, a.value, b.value)
518    }
519
520    pub fn raw_len(&self, value: NativeValue<'a>) -> Option<i64> {
521        match value.value {
522            Value::String(handle) => i64::try_from(self.heap.string_bytes(handle)?.len()).ok(),
523            Value::Table(handle) => Some(self.heap.tables.get(handle)?.table.raw_border()),
524            _ => None,
525        }
526    }
527
528    /// A value's metatable, without `__metatable` protection: a table's
529    /// own, or its type's (ADR 0034). `None` if it has none.
530    pub fn metatable(&self, value: NativeValue<'a>) -> Option<NativeValue<'a>> {
531        let metatable = self.heap.metatable_of(value.value)?;
532        Some(NativeValue::wrap(Value::Table(metatable)))
533    }
534
535    /// Set or clear a table's or a full userdata's own metatable, without
536    /// `__metatable` protection. `false` if `object` is neither, or
537    /// `metatable` is neither a table nor absent.
538    pub fn set_metatable(
539        &mut self,
540        object: NativeValue<'a>,
541        metatable: Option<NativeValue<'a>>,
542    ) -> bool {
543        let metatable = match metatable.map(|value| value.value) {
544            None => None,
545            Some(Value::Table(metatable)) => Some(metatable),
546            Some(_) => return false,
547        };
548        // The one place a metatable is set registers the object for
549        // finalization when the metatable has `__gc` (ADR 0047).
550        self.heap.set_metatable(object.value, metatable)
551    }
552
553    /// A new full userdata with `len` zeroed bytes Lua cannot read and
554    /// `user_values` nil user values (ADR 0042).
555    pub fn new_userdata(
556        &mut self,
557        len: usize,
558        user_values: usize,
559    ) -> Result<NativeValue<'a>, UserdataError> {
560        if len > crate::userdata::MAX_USERDATA_BYTES {
561            self.out_of_memory = true;
562            return Err(UserdataError::Memory);
563        }
564        let made = self
565            .heap
566            .alloc_userdata(self.max_objects, user_values, len as u64, || {
567                crate::userdata::Payload::Bytes(vec![0; len].into_boxed_slice())
568            });
569        self.made(made)
570    }
571
572    /// A new full userdata holding `value`, of a type registered with the
573    /// runtime's registry, with `user_values` nil user values. It counts
574    /// `value.logical_size()` bytes (ADR 0044).
575    pub fn new_host_userdata<T: crate::userdata::HostUserdata>(
576        &mut self,
577        value: T,
578        user_values: usize,
579    ) -> Result<NativeValue<'a>, UserdataError> {
580        if !self.registry.has_userdata_type::<T>() {
581            return Err(UserdataError::Unregistered);
582        }
583        let charge = value.logical_size();
584        let made = self
585            .heap
586            .alloc_userdata(self.max_objects, user_values, charge, || {
587                crate::userdata::Payload::Host {
588                    symbol: T::SYMBOL,
589                    value: Box::new(value),
590                }
591            });
592        self.made(made)
593    }
594
595    fn made(
596        &mut self,
597        made: Result<crate::id::Handle<crate::heap::UserdataObj>, crate::id::TerminationReason>,
598    ) -> Result<NativeValue<'a>, UserdataError> {
599        match made {
600            Ok(handle) => Ok(NativeValue::wrap(Value::Userdata(handle))),
601            Err(_) => {
602                self.out_of_memory = true;
603                Err(UserdataError::Memory)
604            }
605        }
606    }
607
608    /// A light userdata with the host's key (ADR 0043).
609    pub fn light_userdata(&self, key: crate::userdata::HostLightKey) -> NativeValue<'a> {
610        NativeValue::wrap(Value::LightUserdata(crate::value::LightDomain::Host, key.0))
611    }
612
613    /// A light userdata's identity; `None` for anything else.
614    pub fn light(&self, value: NativeValue<'a>) -> Option<crate::userdata::LightUserdata> {
615        match value.value {
616            Value::LightUserdata(domain, bits) => {
617                Some(crate::userdata::LightUserdata { domain, bits })
618            }
619            _ => None,
620        }
621    }
622
623    /// Whether `value` is a full userdata.
624    pub fn is_full_userdata(&self, value: NativeValue<'a>) -> bool {
625        matches!(value.value, Value::Userdata(_))
626    }
627
628    fn userdata_object(&self, value: NativeValue<'a>) -> Option<&crate::heap::UserdataObj> {
629        match value.value {
630            Value::Userdata(handle) => self.heap.userdata.get(handle),
631            _ => None,
632        }
633    }
634
635    fn userdata_object_mut(
636        &mut self,
637        value: NativeValue<'a>,
638    ) -> Option<&mut crate::heap::UserdataObj> {
639        match value.value {
640            Value::Userdata(handle) => self.heap.userdata.get_mut(handle),
641            _ => None,
642        }
643    }
644
645    /// A byte userdata's bytes, borrowed for no longer than the call can
646    /// do nothing else.
647    pub fn userdata_bytes(&self, value: NativeValue<'a>) -> Option<&[u8]> {
648        self.userdata_object(value)?.payload.bytes()
649    }
650
651    pub fn userdata_bytes_mut(&mut self, value: NativeValue<'a>) -> Option<&mut [u8]> {
652        self.userdata_object_mut(value)?.payload.bytes_mut()
653    }
654
655    /// The host value of a full userdata, if it is a `T`. The borrow holds
656    /// the call: nothing that could run Lua or collect can happen while
657    /// it lives, and a native function never calls Lua.
658    pub fn userdata_ref<T: crate::userdata::HostUserdata>(
659        &self,
660        value: NativeValue<'a>,
661    ) -> Option<&T> {
662        self.userdata_object(value)?.payload.host::<T>()
663    }
664
665    /// The borrow is the call's: while it lives, no other borrow of any
666    /// userdata, and no other use of the call, compiles.
667    ///
668    /// ```compile_fail
669    /// use moonseed::{NativeCall, NativeOutcome, ProofCounter};
670    /// fn twice(call: &mut NativeCall<'_>) -> NativeOutcome {
671    ///     let this = call.arg(0);
672    ///     let first = call.userdata_mut::<ProofCounter>(this);
673    ///     let second = call.userdata_mut::<ProofCounter>(this);
674    ///     first.map(|counter| counter.count += 1);
675    ///     NativeOutcome::Ready
676    /// }
677    /// ```
678    ///
679    /// ```compile_fail
680    /// use moonseed::{NativeCall, NativeOutcome, ProofCounter};
681    /// fn held(call: &mut NativeCall<'_>) -> NativeOutcome {
682    ///     let this = call.arg(0);
683    ///     let counter = call.userdata_mut::<ProofCounter>(this).unwrap();
684    ///     call.push_integer(1);
685    ///     counter.count += 1;
686    ///     NativeOutcome::Ready
687    /// }
688    /// ```
689    pub fn userdata_mut<T: crate::userdata::HostUserdata>(
690        &mut self,
691        value: NativeValue<'a>,
692    ) -> Option<&mut T> {
693        self.userdata_object_mut(value)?.payload.host_mut::<T>()
694    }
695
696    /// User value `n` (1-based) of a full userdata; `None` if `value` is
697    /// not one or has no such user value.
698    pub fn user_value(&self, value: NativeValue<'a>, n: usize) -> Option<NativeValue<'a>> {
699        let object = self.userdata_object(value)?;
700        let held = *object.user_values.get(n.checked_sub(1)?)?;
701        Some(NativeValue::wrap(held))
702    }
703
704    /// Set user value `n` (1-based); `false` if there is no such slot.
705    pub fn set_user_value(
706        &mut self,
707        value: NativeValue<'a>,
708        n: usize,
709        held: NativeValue<'a>,
710    ) -> bool {
711        let Some(slot) = n
712            .checked_sub(1)
713            .and_then(|index| self.userdata_object_mut(value)?.user_values.get_mut(index))
714        else {
715            return false;
716        };
717        *slot = held.value;
718        true
719    }
720
721    /// Change the logical bytes a host value counts, as it grows or
722    /// shrinks (ADR 0044). Growth past the logical-heap quota is refused
723    /// before it is counted.
724    pub fn set_userdata_charge(
725        &mut self,
726        value: NativeValue<'a>,
727        bytes: u64,
728    ) -> Result<(), UserdataError> {
729        let Value::Userdata(handle) = value.value else {
730            return Err(UserdataError::NotUserdata);
731        };
732        let object = self
733            .heap
734            .userdata
735            .get(handle)
736            .ok_or(UserdataError::NotUserdata)?;
737        if object.payload.symbol().is_none() {
738            return Err(UserdataError::NotUserdata);
739        }
740        let old = object.charge;
741        if bytes > old && !self.heap.gc.fits(bytes - old) {
742            self.out_of_memory = true;
743            return Err(UserdataError::Memory);
744        }
745        // Growth is charged; a shrink leaves the logical heap at once, so
746        // shrinking and growing again within one call does not count
747        // twice.
748        if bytes > old {
749            self.heap.gc.charge(bytes - old);
750        } else {
751            self.heap.give_back(old - bytes);
752        }
753        if let Some(object) = self.heap.userdata.get_mut(handle) {
754            object.charge = bytes;
755        }
756        Ok(())
757    }
758
759    /// Record Lua's argument error for argument `index` (0-based),
760    /// The caller's name, argument number, and `message` are combined on
761    /// the cold error path as `luaL_argerror` does. Return it to raise it.
762    pub fn arg_error(&mut self, index: usize, message: &str) -> NativeOutcome {
763        self.error = Some(NativeError::Argument(index, message.as_bytes().to_vec()));
764        NativeOutcome::Fault
765    }
766
767    /// Raise a `luaL_error`-style native message.
768    pub fn error(&mut self, message: &str) -> NativeOutcome {
769        self.error = Some(NativeError::Message(message.as_bytes().to_vec(), true));
770        NativeOutcome::Fault
771    }
772
773    /// Raise a VM primitive error, which has no `luaL_where` prefix.
774    pub fn raw_error(&mut self, message: &str) -> NativeOutcome {
775        self.error = Some(NativeError::Message(message.as_bytes().to_vec(), false));
776        NativeOutcome::Fault
777    }
778
779    /// Record Lua's argument error for argument `index` (0-based), as
780    /// `luaL_typeerror` words it using the call-site name and actual type.
781    /// Return it to raise it.
782    pub fn type_error(&mut self, index: usize, expected: &str) -> NativeOutcome {
783        let got: Vec<u8> = if index >= self.args.len() {
784            b"no value".to_vec()
785        } else {
786            let value = self.args[index];
787            match crate::index::metamethod(self.heap, value, b"__name") {
788                Some(Value::String(name)) => {
789                    self.heap.string_bytes(name).unwrap_or_default().to_vec()
790                }
791                _ if matches!(value, Value::LightUserdata(..)) => b"light userdata".to_vec(),
792                _ => crate::heap::type_name(value).as_bytes().to_vec(),
793            }
794        };
795        let mut message = format!("{expected} expected, got ").into_bytes();
796        message.extend(got);
797        self.error = Some(NativeError::Argument(index, message));
798        NativeOutcome::Fault
799    }
800
801    pub fn push(&mut self, value: NativeValue<'a>) {
802        self.results.push(value.value);
803    }
804
805    /// Argument `index` if it is an integer.
806    pub fn integer(&self, index: usize) -> Option<i64> {
807        match self.args.get(index)? {
808            Value::Integer(integer) => Some(*integer),
809            _ => None,
810        }
811    }
812
813    /// Argument `index` if it is a number, converted to a float.
814    pub fn number(&self, index: usize) -> Option<f64> {
815        match self.args.get(index)? {
816            Value::Integer(integer) => Some(*integer as f64),
817            Value::Float(float) => Some(*float),
818            _ => None,
819        }
820    }
821
822    pub fn boolean(&self, index: usize) -> Option<bool> {
823        match self.args.get(index)? {
824            Value::Bool(bit) => Some(*bit),
825            _ => None,
826        }
827    }
828
829    /// True for a nil argument and for one past the end.
830    pub fn is_nil(&self, index: usize) -> bool {
831        matches!(self.args.get(index), None | Some(Value::Nil))
832    }
833
834    pub fn push_integer(&mut self, value: i64) {
835        self.results.push(Value::Integer(value));
836    }
837
838    pub fn push_number(&mut self, value: f64) {
839        self.results.push(Value::Float(value));
840    }
841
842    pub fn push_boolean(&mut self, value: bool) {
843        self.results.push(Value::Bool(value));
844    }
845
846    pub fn push_nil(&mut self) {
847        self.results.push(Value::Nil);
848    }
849
850    /// Return argument `index` unchanged, whatever its type (nil if absent).
851    pub fn push_arg(&mut self, index: usize) {
852        self.results
853            .push(self.args.get(index).copied().unwrap_or(Value::Nil));
854    }
855
856    /// This call's effect id. `Some` only for [`NativePolicy::External`].
857    pub fn effect(&self) -> Option<EffectId> {
858        self.effect
859    }
860
861    /// The embedder's journal. `Some` only for [`NativePolicy::External`].
862    pub fn journal(&mut self) -> Option<&mut Journal> {
863        self.journal.as_deref_mut()
864    }
865}
866
867#[derive(Clone)]
868pub(crate) struct NativeEntry {
869    pub(crate) policy: NativePolicy,
870    pub(crate) function: NativeFn,
871    pub(crate) callback: Option<std::rc::Rc<crate::api::native::Callback>>,
872    pub(crate) typed: Option<std::rc::Rc<crate::api::native::TypedCallback>>,
873    /// A function the VM implements itself because it calls Lua or
874    /// raises an error: `pcall`, `xpcall`, `error`. Its `function` is never
875    /// called.
876    pub(crate) builtin: Option<Builtin>,
877}
878
879/// The base functions that need the VM rather than a `NativeCall`: they
880/// raise errors, call Lua, make strings or native values, or act on the
881/// collector or the output (ADR 0024, ADR 0031).
882#[derive(Clone, Copy, Debug, PartialEq, Eq)]
883pub(crate) enum Builtin {
884    /// The runtime mechanism that the OS lane registers as `os.exit`.
885    #[allow(dead_code)] // Registered by the OS lane; this lane installs no OS library.
886    Exit,
887    Os(crate::oslib::OsFn),
888    Io(crate::iolib::IoFn),
889    #[cfg(test)]
890    CapabilitySmoke,
891    Pcall,
892    Xpcall,
893    Error,
894    Assert,
895    Type,
896    ToString,
897    ToNumber,
898    Print,
899    Next,
900    Pairs,
901    Ipairs,
902    /// The iterator `ipairs` returns.
903    IpairsNext,
904    CollectGarbage,
905    Load,
906    LoadFile,
907    DoFile,
908    /// A `math` function (ADR 0032).
909    Math(crate::library::MathFn),
910    /// A `table` function (ADR 0033).
911    Table(crate::library::TableFn),
912    /// A `string` function, or a string metamethod (ADR 0034).
913    String(crate::strlib::StrFn),
914    /// A UTF-8 function or stable iterator.
915    Utf8(crate::utf8lib::Utf8Fn),
916    /// `require` or a `package` searcher (ADR 0039).
917    Package(crate::package::PkgFn),
918    /// A `debug` function (ADR 0040).
919    Debug(crate::debuglib::DbgFn),
920    /// A `coroutine` function (ADR 0041).
921    Coroutine(crate::corolib::CoFn),
922    /// `warn` (ADR 0049).
923    Warn,
924}
925
926/// Where `print` writes (ADR 0031). Host state, not snapshot state: a
927/// restored runtime has none until the host sets one, and without one
928/// `print` writes nothing. Each write is one external effect, committed
929/// through the journal, so a replayed effect is not written twice.
930/// Unstable API.
931pub type Output = Box<dyn FnMut(&[u8])>;
932
933/// Where warnings go (ADR 0049): `warn`'s and those of failed finalizers.
934/// Host state, like the output sink. A warning is one external effect, given
935/// to the sink as pieces; the flag is Lua's `tocont`, true for every
936/// piece but the last. Control messages (a single piece starting with
937/// `@`, such as `@on` and `@off`) are passed on: what they mean is the
938/// sink's choice, as it is the warning function's in Lua. Unstable API.
939pub type Warnings = Box<dyn FnMut(&[u8], bool)>;
940
941/// Where `math.randomseed()` with no argument gets its two seed words
942/// (ADR 0032). Host state, not snapshot state. Each word is an external
943/// effect committed through the journal. Unstable API.
944pub type Entropy = Box<dyn FnMut() -> i64>;
945
946fn builtin_placeholder(_call: &mut NativeCall<'_>) -> NativeOutcome {
947    NativeOutcome::Fault
948}
949
950type HookEntries = Vec<(String, std::rc::Rc<crate::api::hooks::HookCallback>)>;
951
952/// Host native callbacks and userdata registrations, bound by stable symbols.
953/// Cloning shares callback objects, not mutable registration maps. A runtime
954/// owns its registry; Lua captures belong in [`crate::Runtime::make_closure`],
955/// while Rust callback state remains host-owned and is not checkpointed.
956/// Rebuild host registrations before [`crate::Runtime::restore`]; Moonseed
957/// supplies its allowed library symbols through [`crate::Host`]. Missing symbols
958/// fail with [`crate::SnapshotError::UnknownHostSymbol`]; userdata codecs and
959/// policies must match. Typed argument failures become catchable Lua errors;
960/// other misuse remains [`crate::ApiError`]. Callback panics propagate and poison
961/// execution/snapshots: discard the runtime if the host catches one.
962///
963/// ```
964/// use moonseed::{HostRegistry, NativePolicy, Runtime};
965/// let mut registry = HostRegistry::new();
966/// registry.typed("example.double", NativePolicy::VmLocal, |_, n: i64| Ok(n.wrapping_mul(2)));
967/// let mut rt = Runtime::builder().registry(registry).build()?;
968/// let double = rt.make_closure("example.double", ())?;
969/// rt.globals().raw_set(&mut rt, "double", double)?;
970/// # Ok::<(), moonseed::Error>(())
971/// ```
972#[derive(Clone)]
973pub struct HostRegistry {
974    entries: Vec<(String, HostFn)>,
975    natives: Vec<(String, NativeEntry)>,
976    /// Host userdata types, by symbol (ADR 0044).
977    userdata_types: Vec<crate::userdata::HostType>,
978    hooks: Option<Box<HookEntries>>,
979}
980
981impl HostRegistry {
982    /// Create an empty native and userdata registry.
983    pub fn new() -> Self {
984        Self {
985            entries: Vec::new(),
986            natives: Vec::new(),
987            userdata_types: Vec::new(),
988            hooks: None,
989        }
990    }
991
992    /// Register a synchronous debug hook under a stable snapshot symbol.
993    /// Re-registering a symbol replaces its callback without changing its slot.
994    pub fn register_hook<F>(&mut self, symbol: impl Into<String>, callback: F)
995    where
996        F: Fn(&mut crate::HookContext<'_>) -> crate::Result<crate::HookAction> + 'static,
997    {
998        let symbol = symbol.into();
999        let hooks = self.hooks.get_or_insert_with(Box::default);
1000        let entry = (
1001            symbol.clone(),
1002            std::rc::Rc::new(callback) as std::rc::Rc<crate::api::hooks::HookCallback>,
1003        );
1004        if let Some(slot) = hooks.iter().position(|(name, _)| name == &symbol) {
1005            hooks[slot] = entry;
1006        } else {
1007            hooks.push(entry);
1008        }
1009    }
1010    pub(crate) fn hook_slot(&self, symbol: &str) -> Option<u32> {
1011        self.hooks
1012            .as_ref()?
1013            .iter()
1014            .position(|(name, _)| name == symbol)
1015            .and_then(|i| i.try_into().ok())
1016    }
1017    pub(crate) fn hook(
1018        &self,
1019        slot: u32,
1020    ) -> Option<(&str, &std::rc::Rc<crate::api::hooks::HookCallback>)> {
1021        self.hooks
1022            .as_ref()?
1023            .get(slot as usize)
1024            .map(|(name, callback)| (name.as_str(), callback))
1025    }
1026
1027    /// Register a host userdata type that snapshots refuse (ADR 0045): a
1028    /// snapshot of a heap holding one fails with
1029    /// [`crate::SnapshotError::NonPortableUserdata`]. The safe choice for
1030    /// anything holding a handle, a lock, or an address. A later
1031    /// registration of the same symbol replaces it.
1032    pub fn register_userdata<T: crate::userdata::HostUserdata>(&mut self) {
1033        self.insert_userdata_type(crate::userdata::HostType::of::<T>());
1034    }
1035
1036    /// Register a host userdata type that snapshots carry through its
1037    /// codec (ADR 0045). A restore needs the same symbol registered as
1038    /// portable.
1039    pub fn register_portable_userdata<T: crate::userdata::PortableUserdata>(&mut self) {
1040        self.insert_userdata_type(crate::userdata::HostType::portable::<T>());
1041    }
1042
1043    /// Register a type whose snapshots contain only a bounded external key.
1044    /// Restore requires the same policy and resources in the host environment.
1045    pub fn register_rebind_userdata<T: crate::userdata::RebindUserdata>(&mut self) {
1046        self.insert_userdata_type(crate::userdata::HostType::rebind::<T>());
1047    }
1048
1049    /// Inspect the snapshot policy registered under this host type symbol.
1050    pub fn userdata_policy(&self, symbol: &str) -> Option<crate::UserdataPolicy> {
1051        self.userdata_type(symbol).map(|entry| entry.policy.kind())
1052    }
1053
1054    fn insert_userdata_type(&mut self, entry: crate::userdata::HostType) {
1055        self.userdata_types
1056            .retain(|held| held.symbol != entry.symbol && held.type_id != entry.type_id);
1057        self.userdata_types.push(entry);
1058    }
1059
1060    pub(crate) fn has_userdata_type<T: 'static>(&self) -> bool {
1061        let type_id = std::any::TypeId::of::<T>();
1062        self.userdata_types
1063            .iter()
1064            .any(|entry| entry.type_id == type_id)
1065    }
1066
1067    pub(crate) fn userdata_type(&self, symbol: &str) -> Option<crate::userdata::HostType> {
1068        self.userdata_types
1069            .iter()
1070            .find(|entry| entry.symbol == symbol)
1071            .copied()
1072    }
1073
1074    /// Register a native function under a stable symbol. The symbol is its
1075    /// identity in Lua and in snapshots; a later registration of the same
1076    /// symbol replaces the implementation.
1077    pub fn register_native(
1078        &mut self,
1079        symbol: impl Into<String>,
1080        policy: NativePolicy,
1081        function: NativeFn,
1082    ) {
1083        self.insert_native(
1084            symbol.into(),
1085            NativeEntry {
1086                policy,
1087                function,
1088                callback: None,
1089                typed: None,
1090                builtin: None,
1091            },
1092        );
1093    }
1094
1095    /// Register a callback under its stable snapshot symbol. Rust callback
1096    /// state is host state; Lua captures belong in a native closure.
1097    pub fn function<F>(&mut self, symbol: impl Into<String>, policy: NativePolicy, f: F)
1098    where
1099        F: Fn(&mut crate::NativeContext<'_>) -> crate::Result<crate::NativeReturn> + 'static,
1100    {
1101        self.insert_native(
1102            symbol.into(),
1103            NativeEntry {
1104                policy,
1105                function: builtin_placeholder,
1106                callback: Some(std::rc::Rc::new(f)),
1107                typed: None,
1108                builtin: None,
1109            },
1110        );
1111    }
1112
1113    /// Register a typed callback. Argument conversion failures raise Lua's
1114    /// positioned argument error; other API failures remain host errors.
1115    pub fn typed<A, R, F>(&mut self, symbol: impl Into<String>, policy: NativePolicy, f: F)
1116    where
1117        A: crate::FromLuaMulti,
1118        R: crate::IntoLuaMulti,
1119        F: Fn(&mut crate::NativeContext<'_>, A) -> crate::Result<R> + 'static,
1120    {
1121        let fast: std::rc::Rc<crate::api::native::TypedCallback> = std::rc::Rc::new(move |cx| {
1122            let args = cx
1123                .arguments::<A>()
1124                .map_err(|error| cx.argument_error(error))?;
1125            let result = f(cx, args)?;
1126            cx.write_results(result)
1127        });
1128        let callback = fast.clone();
1129        self.insert_native(
1130            symbol.into(),
1131            NativeEntry {
1132                policy,
1133                function: builtin_placeholder,
1134                builtin: None,
1135                typed: Some(fast),
1136                callback: Some(std::rc::Rc::new(move |cx| {
1137                    callback(cx)?;
1138                    Ok(crate::NativeReturn::Return(cx.take_results()?))
1139                })),
1140            },
1141        );
1142    }
1143
1144    pub(crate) fn register_builtin(&mut self, symbol: &str, builtin: Builtin) {
1145        self.insert_native(
1146            symbol.to_string(),
1147            NativeEntry {
1148                policy: NativePolicy::VmLocal,
1149                function: builtin_placeholder,
1150                callback: None,
1151                typed: None,
1152                builtin: Some(builtin),
1153            },
1154        );
1155    }
1156
1157    fn insert_native(&mut self, symbol: String, entry: NativeEntry) {
1158        if let Some(slot) = self.natives.iter().position(|(name, _)| name == &symbol) {
1159            self.natives[slot] = (symbol, entry);
1160        } else {
1161            self.natives.push((symbol, entry));
1162        }
1163    }
1164
1165    pub(crate) fn fill_missing_natives(&mut self, source: &Self) {
1166        for (symbol, entry) in &source.natives {
1167            if self.native_slot(symbol).is_none() {
1168                self.insert_native(symbol.clone(), entry.clone());
1169            }
1170        }
1171    }
1172
1173    pub(crate) fn native_slot(&self, symbol: &str) -> Option<usize> {
1174        self.natives.iter().position(|(name, _)| name == symbol)
1175    }
1176
1177    pub(crate) fn native(&self, slot: usize) -> Option<&NativeEntry> {
1178        self.natives.get(slot).map(|(_, entry)| entry)
1179    }
1180
1181    /// Register an integer-only legacy proof callback.
1182    #[deprecated(note = "use HostRegistry::function or HostRegistry::typed")]
1183    pub(crate) fn register(&mut self, symbol: impl Into<String>, function: HostFn) {
1184        let symbol = symbol.into();
1185        if let Some(slot) = self.entries.iter().position(|(name, _)| name == &symbol) {
1186            self.entries[slot] = (symbol, function);
1187        } else {
1188            self.entries.push((symbol, function));
1189        }
1190    }
1191
1192    #[doc(hidden)] // Kernel proof fixture; outside the embedding API.
1193    pub fn proof() -> Self {
1194        let mut registry = Self::new();
1195        registry.register("mark", mark);
1196        registry.register("park", park);
1197        registry.register_native("add", NativePolicy::VmLocal, native_add);
1198        registry.register_native("sub", NativePolicy::VmLocal, native_sub);
1199        registry.register_native("many", NativePolicy::VmLocal, native_many);
1200        registry.register_native("none", NativePolicy::VmLocal, native_none);
1201        registry.register_native("mark", NativePolicy::External, native_mark);
1202        registry.register_native("park", NativePolicy::VmLocal, native_park);
1203        registry.register_native("second", NativePolicy::VmLocal, native_second);
1204        registry.register_native("upto", NativePolicy::VmLocal, native_upto);
1205        register_userdata_proof(&mut registry);
1206        crate::library::register_standard(&mut registry);
1207        crate::debuglib::register_debug(&mut registry);
1208        registry
1209    }
1210
1211    pub(crate) fn contains(&self, symbol: &str) -> bool {
1212        self.entries.iter().any(|(name, _)| name == symbol)
1213    }
1214
1215    pub(crate) fn call(&self, symbol: &str, ctx: &mut HostCtx<'_>, arg: i64) -> Option<HostResult> {
1216        let function = self.entries.iter().find(|(name, _)| name == symbol)?.1;
1217        Some(function(ctx, arg))
1218    }
1219}
1220
1221impl Default for HostRegistry {
1222    fn default() -> Self {
1223        Self::new()
1224    }
1225}
1226
1227/// Bounded host effect. The returned outcome is the sequence, unless the
1228/// journal already committed a different outcome for this [`EffectId`].
1229pub fn mark(ctx: &mut HostCtx<'_>, arg: i64) -> HostResult {
1230    let effect = ctx.effect;
1231    let outcome = ctx.journal.commit(effect, arg, || effect.sequence as i64);
1232    match outcome {
1233        Ok(outcome) => HostResult::Ready(outcome),
1234        Err(_) => HostResult::Fault,
1235    }
1236}
1237
1238/// Parks the caller until [`crate::Runtime::complete_wait`]. Does not commit.
1239pub fn park(_ctx: &mut HostCtx<'_>, _arg: i64) -> HostResult {
1240    HostResult::Pending(WaitKey(1))
1241}
1242
1243/// `add(a, b)`: integer sum, wrapping. Faults unless both are integers.
1244pub fn native_add(call: &mut NativeCall<'_>) -> NativeOutcome {
1245    match (call.integer(0), call.integer(1)) {
1246        (Some(a), Some(b)) => {
1247            call.push_integer(a.wrapping_add(b));
1248            NativeOutcome::Ready
1249        }
1250        _ => NativeOutcome::Fault,
1251    }
1252}
1253
1254/// `sub(a, b)`: like `add`, a different symbol for identity tests.
1255pub fn native_sub(call: &mut NativeCall<'_>) -> NativeOutcome {
1256    match (call.integer(0), call.integer(1)) {
1257        (Some(a), Some(b)) => {
1258            call.push_integer(a.wrapping_sub(b));
1259            NativeOutcome::Ready
1260        }
1261        _ => NativeOutcome::Fault,
1262    }
1263}
1264
1265/// `many()`: returns `10, nil, 30`.
1266pub fn native_many(call: &mut NativeCall<'_>) -> NativeOutcome {
1267    call.push_integer(10);
1268    call.push_nil();
1269    call.push_integer(30);
1270    NativeOutcome::Ready
1271}
1272
1273/// `none()`: returns nothing.
1274pub fn native_none(_call: &mut NativeCall<'_>) -> NativeOutcome {
1275    NativeOutcome::Ready
1276}
1277
1278/// `mark(x)`: the proof kernel's effect as a native function. Commits
1279/// through the journal, so a replayed effect id returns the stored outcome.
1280pub fn native_mark(call: &mut NativeCall<'_>) -> NativeOutcome {
1281    let (Some(effect), Some(arg)) = (call.effect(), call.integer(0)) else {
1282        return NativeOutcome::Fault;
1283    };
1284    let Some(journal) = call.journal() else {
1285        return NativeOutcome::Fault;
1286    };
1287    let Ok(outcome) = journal.commit(effect, arg, || effect.sequence as i64) else {
1288        return NativeOutcome::Fault;
1289    };
1290    call.push_integer(outcome);
1291    NativeOutcome::Ready
1292}
1293
1294/// `park()`: waits for [`crate::Runtime::complete_wait`] with key 1.
1295pub fn native_park(_call: &mut NativeCall<'_>) -> NativeOutcome {
1296    NativeOutcome::Pending(WaitKey(1))
1297}
1298
1299/// `second(a, b)`: returns `b`. As `__index`, returns the key.
1300pub fn native_second(call: &mut NativeCall<'_>) -> NativeOutcome {
1301    call.push_arg(1);
1302    NativeOutcome::Ready
1303}
1304
1305/// `upto(n, i)`: an iterator. Returns `i + 1`, or 1 for a nil `i`, while
1306/// that is at most `n`; then nothing.
1307pub fn native_upto(call: &mut NativeCall<'_>) -> NativeOutcome {
1308    let last = if call.is_nil(1) {
1309        Some(0)
1310    } else {
1311        call.integer(1)
1312    };
1313    match (call.integer(0), last.and_then(|last| last.checked_add(1))) {
1314        (Some(n), Some(next)) => {
1315            if next <= n {
1316                call.push_integer(next);
1317            }
1318            NativeOutcome::Ready
1319        }
1320        _ => NativeOutcome::Fault,
1321    }
1322}
1323
1324/// Userdata proof natives (ADR 0042 to ADR 0045): what a host gives Lua to
1325/// make and use userdata, as the reference harness gives Lua 5.4.9 through
1326/// its C API. `newud(size [, nuv])` makes a byte userdata, `light(n)` a
1327/// light userdata with host key `n`, `udpeek(u, i)` and `udpoke(u, i, b)`
1328/// read and write byte `i` (0-based).
1329#[doc(hidden)] // Kernel proof fixture; outside the embedding API.
1330pub const USERDATA_NATIVES: [(&str, NativeFn); 10] = [
1331    ("newud", native_newud),
1332    ("light", native_light),
1333    ("udpeek", native_udpeek),
1334    ("udpoke", native_udpoke),
1335    ("counter_new", native_counter_new),
1336    ("counter_get", native_counter_get),
1337    ("counter_add", native_counter_add),
1338    ("counter_grow", native_counter_grow),
1339    ("handle_new", native_handle_new),
1340    ("handle_get", native_handle_get),
1341];
1342
1343/// Register the userdata proof natives and their host types: the
1344/// portable `ProofCounter` and the snapshot-refusing `ProofHandle`.
1345#[doc(hidden)] // Kernel proof fixture; outside the embedding API.
1346pub fn register_userdata_proof(registry: &mut HostRegistry) {
1347    for (symbol, function) in USERDATA_NATIVES {
1348        registry.register_native(symbol, NativePolicy::VmLocal, function);
1349    }
1350    registry.register_portable_userdata::<ProofCounter>();
1351    registry.register_userdata::<ProofHandle>();
1352}
1353
1354/// A portable host userdata for proofs: a count, and the logical bytes it
1355/// claims, which `counter_grow` changes.
1356#[derive(Debug, PartialEq)]
1357#[doc(hidden)] // Kernel proof fixture; outside the embedding API.
1358pub struct ProofCounter {
1359    pub count: i64,
1360    pub size: u64,
1361}
1362
1363impl crate::userdata::HostUserdata for ProofCounter {
1364    const SYMBOL: &'static str = "moonseed.Counter";
1365    fn logical_size(&self) -> u64 {
1366        self.size
1367    }
1368}
1369
1370impl crate::userdata::PortableUserdata for ProofCounter {
1371    fn encode(&self) -> Vec<u8> {
1372        let mut bytes = self.count.to_le_bytes().to_vec();
1373        bytes.extend(self.size.to_le_bytes());
1374        bytes
1375    }
1376
1377    fn decode(bytes: &[u8]) -> Option<Self> {
1378        let (count, size) = bytes.split_at_checked(8)?;
1379        Some(Self {
1380            count: i64::from_le_bytes(count.try_into().ok()?),
1381            size: u64::from_le_bytes(size.try_into().ok()?),
1382        })
1383    }
1384}
1385
1386/// A host userdata no snapshot carries, as a file handle or a lock would
1387/// be.
1388#[derive(Debug)]
1389#[doc(hidden)] // Kernel proof fixture; outside the embedding API.
1390pub struct ProofHandle(pub i64);
1391
1392impl crate::userdata::HostUserdata for ProofHandle {
1393    const SYMBOL: &'static str = "moonseed.Handle";
1394    fn logical_size(&self) -> u64 {
1395        8
1396    }
1397}
1398
1399fn native_newud(call: &mut NativeCall<'_>) -> NativeOutcome {
1400    let size = call.integer(0).and_then(|size| usize::try_from(size).ok());
1401    let user_values = if call.is_nil(1) {
1402        Some(0)
1403    } else {
1404        call.integer(1).and_then(|n| usize::try_from(n).ok())
1405    };
1406    let (Some(size), Some(user_values)) = (size, user_values) else {
1407        return NativeOutcome::Fault;
1408    };
1409    match call.new_userdata(size, user_values) {
1410        Ok(userdata) => {
1411            call.push(userdata);
1412            NativeOutcome::Ready
1413        }
1414        Err(_) => NativeOutcome::Fault,
1415    }
1416}
1417
1418fn native_light(call: &mut NativeCall<'_>) -> NativeOutcome {
1419    let Some(key) = call.integer(0) else {
1420        return NativeOutcome::Fault;
1421    };
1422    let light = call.light_userdata(crate::userdata::HostLightKey(key as u64));
1423    call.push(light);
1424    NativeOutcome::Ready
1425}
1426
1427fn native_udpeek(call: &mut NativeCall<'_>) -> NativeOutcome {
1428    let userdata = call.arg(0);
1429    let byte = call
1430        .integer(1)
1431        .and_then(|index| usize::try_from(index).ok())
1432        .and_then(|index| call.userdata_bytes(userdata)?.get(index).copied());
1433    match byte {
1434        Some(byte) => {
1435            call.push_integer(i64::from(byte));
1436            NativeOutcome::Ready
1437        }
1438        None => NativeOutcome::Fault,
1439    }
1440}
1441
1442fn native_udpoke(call: &mut NativeCall<'_>) -> NativeOutcome {
1443    let userdata = call.arg(0);
1444    let (Some(index), Some(byte)) = (call.integer(1), call.integer(2)) else {
1445        return NativeOutcome::Fault;
1446    };
1447    let slot = usize::try_from(index)
1448        .ok()
1449        .and_then(|index| call.userdata_bytes_mut(userdata)?.get_mut(index));
1450    match slot {
1451        Some(slot) => {
1452            *slot = byte as u8;
1453            NativeOutcome::Ready
1454        }
1455        None => NativeOutcome::Fault,
1456    }
1457}
1458
1459/// `counter_new(n [, mt [, size]])`: a counter at `n` with metatable `mt`,
1460/// claiming `size` logical bytes (default 16).
1461fn native_counter_new(call: &mut NativeCall<'_>) -> NativeOutcome {
1462    let Some(count) = call.integer(0) else {
1463        return call.type_error(0, "number");
1464    };
1465    let size = call.integer(2).map_or(16, |size| size.max(0) as u64);
1466    let metatable = call.arg(1);
1467    let counter = match call.new_host_userdata(ProofCounter { count, size }, 1) {
1468        Ok(counter) => counter,
1469        Err(_) => return NativeOutcome::Fault,
1470    };
1471    if !call.is_nil(1) && !call.set_metatable(counter, Some(metatable)) {
1472        return call.type_error(1, "table");
1473    }
1474    call.push(counter);
1475    NativeOutcome::Ready
1476}
1477
1478fn native_counter_get(call: &mut NativeCall<'_>) -> NativeOutcome {
1479    let this = call.arg(0);
1480    let Some(counter) = call.userdata_ref::<ProofCounter>(this) else {
1481        return call.type_error(0, ProofCounter::SYMBOL_NAME);
1482    };
1483    let count = counter.count;
1484    call.push_integer(count);
1485    NativeOutcome::Ready
1486}
1487
1488fn native_counter_add(call: &mut NativeCall<'_>) -> NativeOutcome {
1489    let this = call.arg(0);
1490    let Some(by) = call.integer(1) else {
1491        return call.type_error(1, "number");
1492    };
1493    let Some(counter) = call.userdata_mut::<ProofCounter>(this) else {
1494        return call.type_error(0, ProofCounter::SYMBOL_NAME);
1495    };
1496    counter.count = counter.count.wrapping_add(by);
1497    call.push_arg(0);
1498    NativeOutcome::Ready
1499}
1500
1501/// `counter_grow(c, size)`: the counter now claims `size` logical bytes,
1502/// as a host value that grew would report.
1503fn native_counter_grow(call: &mut NativeCall<'_>) -> NativeOutcome {
1504    let this = call.arg(0);
1505    let Some(size) = call.integer(1).and_then(|size| u64::try_from(size).ok()) else {
1506        return call.type_error(1, "number");
1507    };
1508    if call.userdata_ref::<ProofCounter>(this).is_none() {
1509        return call.type_error(0, ProofCounter::SYMBOL_NAME);
1510    }
1511    if call.set_userdata_charge(this, size).is_err() {
1512        return NativeOutcome::Fault;
1513    }
1514    if let Some(counter) = call.userdata_mut::<ProofCounter>(this) {
1515        counter.size = size;
1516    }
1517    NativeOutcome::Ready
1518}
1519
1520fn native_handle_new(call: &mut NativeCall<'_>) -> NativeOutcome {
1521    let Some(n) = call.integer(0) else {
1522        return call.type_error(0, "number");
1523    };
1524    match call.new_host_userdata(ProofHandle(n), 0) {
1525        Ok(handle) => {
1526            call.push(handle);
1527            NativeOutcome::Ready
1528        }
1529        Err(_) => NativeOutcome::Fault,
1530    }
1531}
1532
1533fn native_handle_get(call: &mut NativeCall<'_>) -> NativeOutcome {
1534    let this = call.arg(0);
1535    let Some(handle) = call.userdata_ref::<ProofHandle>(this) else {
1536        return call.type_error(0, ProofHandle::SYMBOL_NAME);
1537    };
1538    let n = handle.0;
1539    call.push_integer(n);
1540    NativeOutcome::Ready
1541}
1542
1543impl ProofCounter {
1544    const SYMBOL_NAME: &'static str = <Self as crate::userdata::HostUserdata>::SYMBOL;
1545}
1546
1547impl ProofHandle {
1548    const SYMBOL_NAME: &'static str = <Self as crate::userdata::HostUserdata>::SYMBOL;
1549}