Skip to main content

rustia/
invocation.rs

1use crate::function::{
2    host_arg_from_raw, host_return_to_raw, FromHostArgument, IntoHostFunction, IntoHostReturn,
3};
4use crate::serde_value::from_live;
5use crate::value::{
6    load_owned_arguments, snapshot_value, FromRustia, FromRustiaMulti, IntoRustiaMulti,
7};
8use crate::{
9    CompiledEntry, CompiledModule, Error, Exports, Result, RustiaHostFuelPolicy,
10    RustiaHostFunctionInfo, Table, Value, RUSTIA_HOST_FUEL_ABI_VERSION, RUSTIA_HOST_FUEL_POLICY,
11};
12use rustia_vm::{
13    Error as VmError, ErrorKind as VmErrorKind, HostFunctionOp, OpCapability, Value as RawValue,
14    Vm, VmExecution, VmHostDispatcher,
15};
16use std::any::type_name;
17use std::convert::Infallible;
18use std::marker::PhantomData;
19use std::panic::{catch_unwind, AssertUnwindSafe};
20
21/// Defines the kinds of data Rustia can exchange with your application.
22///
23/// Implement this trait once for an application integration. It contains no
24/// runtime data and has no methods; it only names the Rust types passed between
25/// your application and its scripts.
26///
27/// Here, an *invocation* means one [`Rustia::invoke`](crate::Rustia::invoke)
28/// operation: the period in which your application lends data to guest code
29/// and collects its outputs.
30///
31/// A useful way to read the two host traits is:
32///
33/// - `HostSchema` says **which types** the integration uses.
34/// - [`HostContext<H>`](HostContext) supplies **the actual values** for one
35///   invocation.
36///
37/// For example, a game might define its integration like this:
38///
39/// ```
40/// # use rustia::HostSchema;
41/// # struct SensorSnapshot;
42/// # struct SavedMemory;
43/// # struct DebugState;
44/// # struct Action;
45/// # struct MemoryChange;
46/// # struct OutputRecord;
47/// struct GameAi;
48///
49/// impl HostSchema for GameAi {
50///     type Input = SensorSnapshot;
51///     type Slots = SavedMemory;
52///     type External = DebugState;
53///     type Effect = Action;
54///     type SlotWrite = MemoryChange;
55///     type Record = OutputRecord;
56/// }
57/// ```
58///
59/// Rust functions exposed to scripts—called *host callbacks*—can request only
60/// the part of this schema they are allowed to use. For example, an input
61/// callback can read `Input`, while an effect callback can only stage an
62/// `Effect`.
63///
64/// # Why the types and values are separate
65///
66/// A [`Rustia<H>`](crate::Rustia) VM and its registered functions can live for
67/// a long time. The [`HostContext`] passed to [`Rustia::invoke`](crate::Rustia::invoke)
68/// is borrowed only while that invocation runs. Keeping them separate means a
69/// short-lived context can safely borrow data from the current frame, tick, or
70/// request; Rustia never stores those borrowed values.
71pub trait HostSchema: Sized + 'static {
72    /// Read-only input for the current invocation, such as a sensor snapshot
73    /// or request data.
74    type Input: ?Sized;
75    /// Read-only saved state, or "slots", that persists between invocations.
76    type Slots: ?Sized;
77    /// Mutable application state for explicitly external or nondeterministic
78    /// callbacks.
79    ///
80    /// [`Profile::DeterministicSim`](crate::Profile::DeterministicSim) rejects
81    /// callbacks with this access before installing them.
82    type External: ?Sized;
83    /// An action or event that a script may stage with [`Effects::emit`].
84    type Effect;
85    /// A proposed change to saved slot state that a script may stage with
86    /// [`SlotWrites::write`].
87    type SlotWrite;
88    /// One output item returned to the application after a successful
89    /// invocation.
90    ///
91    /// [`HostContext::record_effect`] and [`HostContext::record_slot_write`]
92    /// convert effects and slot writes into this common type.
93    type Record;
94}
95
96/// Supplies the actual host data used by one Rustia invocation.
97///
98/// This is usually implemented for a small, short-lived struct containing
99/// references to your application's current data:
100///
101/// ```
102/// # struct SensorSnapshot;
103/// # struct SavedMemory;
104/// # struct DebugState;
105/// struct CurrentTurn<'a> {
106///     sensors: &'a SensorSnapshot,
107///     memory: &'a SavedMemory,
108///     debug: &'a mut DebugState,
109/// }
110/// ```
111///
112/// Pass a value like `CurrentTurn` to [`Rustia::invoke`](crate::Rustia::invoke).
113/// Rustia borrows it only until that invocation finishes and never stores it.
114/// A later invocation may use a completely different context value, borrowing
115/// different application data.
116///
117/// The accessor methods determine what registered host callbacks can see.
118/// Effect and slot-write callbacks do not modify application state directly;
119/// they create `Record` values in Rustia's private staging area. Rustia returns
120/// those records only if the complete invocation succeeds.
121///
122/// # What Rustia can roll back
123///
124/// Rustia can discard staged records, but it cannot undo other mutations.
125/// Implementations should therefore make [`HostContext::input`],
126/// [`HostContext::slots`], the two `record_*` methods, and
127/// [`HostContext::record_bytes`] behave like read-only calculations. Mutation
128/// performed through [`HostMut`]—or hidden behind interior mutability—is
129/// immediate and is not part of the record transaction.
130pub trait HostContext<H>
131where
132    H: HostSchema,
133{
134    /// Returns the read-only input for this invocation.
135    fn input(&self) -> &H::Input;
136
137    /// Returns the read-only persistent state visible to slot-reading
138    /// callbacks.
139    fn slots(&self) -> &H::Slots;
140
141    /// Returns mutable application state for external or nondeterministic
142    /// callbacks.
143    ///
144    /// Rustia calls this only for functions registered through
145    /// [`HostModule::external`] or [`HostModule::nondeterministic`], which
146    /// deterministic profiles reject before installation. Changes made through
147    /// this method take effect immediately and cannot be rolled back by Rustia.
148    fn external_mut(&mut self) -> &mut H::External;
149
150    /// Wraps an emitted effect in the application's common output-record type.
151    ///
152    /// `sequence` starts at zero and increases for each effect or slot write
153    /// staged during this invocation. It can be used to preserve the exact
154    /// order in which the script produced its outputs.
155    fn record_effect(&self, sequence: u32, effect: H::Effect) -> H::Record;
156
157    /// Wraps a staged slot write in the application's common output-record
158    /// type.
159    ///
160    /// Effects and slot writes share the same increasing `sequence`, so their
161    /// relative order is preserved.
162    fn record_slot_write(&self, sequence: u32, write: H::SlotWrite) -> H::Record;
163
164    /// Reports how many logical bytes this record should consume from the
165    /// invocation's output budget.
166    ///
167    /// This is application-defined accounting rather than Rust's in-memory
168    /// object size. It must return the same answer for the same record when
169    /// deterministic execution is required.
170    fn record_bytes(&self, record: &H::Record) -> u64;
171}
172
173impl HostSchema for () {
174    type Input = ();
175    type Slots = ();
176    type External = ();
177    type Effect = Infallible;
178    type SlotWrite = Infallible;
179    type Record = Infallible;
180}
181
182impl HostContext<()> for () {
183    fn input(&self) -> &() {
184        self
185    }
186
187    fn slots(&self) -> &() {
188        self
189    }
190
191    fn external_mut(&mut self) -> &mut () {
192        self
193    }
194
195    fn record_effect(&self, _sequence: u32, effect: Infallible) -> Infallible {
196        match effect {}
197    }
198
199    fn record_slot_write(&self, _sequence: u32, write: Infallible) -> Infallible {
200        match write {}
201    }
202
203    fn record_bytes(&self, record: &Infallible) -> u64 {
204        match *record {}
205    }
206}
207
208/// Fuel and output limits shared by calls within one invocation.
209///
210/// Record publication is disabled by default. Enable its independent count
211/// and logical-byte budgets explicitly:
212///
213/// ```
214/// use rustia::InvocationLimits;
215///
216/// let limits = InvocationLimits::new(50_000)
217///     .with_max_records(32)
218///     .with_max_record_bytes(4 * 1024);
219/// ```
220#[derive(Clone, Copy, Debug, Eq, PartialEq)]
221pub struct InvocationLimits {
222    fuel: u64,
223    max_records: u32,
224    max_record_bytes: u64,
225}
226
227impl InvocationLimits {
228    /// Creates an invocation budget with `fuel` execution units and record
229    /// publication disabled. If the VM also has a configured builder/settings
230    /// fuel limit, the lower value is the effective invocation budget.
231    pub const fn new(fuel: u64) -> Self {
232        Self {
233            fuel,
234            max_records: 0,
235            max_record_bytes: 0,
236        }
237    }
238
239    /// Sets the maximum number of records that may be staged.
240    #[must_use]
241    pub const fn with_max_records(mut self, max_records: u32) -> Self {
242        self.max_records = max_records;
243        self
244    }
245
246    /// Sets the maximum total logical bytes of staged records.
247    #[must_use]
248    pub const fn with_max_record_bytes(mut self, max_record_bytes: u64) -> Self {
249        self.max_record_bytes = max_record_bytes;
250        self
251    }
252
253    /// Returns the shared guest-and-host execution fuel budget.
254    pub const fn fuel(self) -> u64 {
255        self.fuel
256    }
257
258    /// Returns the staged-record count limit.
259    pub const fn max_records(self) -> u32 {
260        self.max_records
261    }
262
263    /// Returns the staged-record logical-byte limit.
264    pub const fn max_record_bytes(self) -> u64 {
265        self.max_record_bytes
266    }
267}
268
269/// Resources consumed by one successful invocation.
270#[derive(Clone, Copy, Debug, Eq, PartialEq)]
271pub struct InvocationUsage {
272    pub(crate) fuel_used: u64,
273    pub(crate) record_count: u32,
274    pub(crate) record_bytes: u64,
275}
276
277impl InvocationUsage {
278    pub const fn fuel_used(self) -> u64 {
279        self.fuel_used
280    }
281
282    pub const fn record_count(self) -> u32 {
283        self.record_count
284    }
285
286    pub const fn record_bytes(self) -> u64 {
287        self.record_bytes
288    }
289}
290
291/// The return value, output records, and resource usage of a successful invocation.
292///
293/// Records borrow Rustia's reusable journal until the next mutable use of that VM.
294#[derive(Debug)]
295pub struct InvocationOutcome<'a, T, Record> {
296    pub(crate) value: T,
297    pub(crate) records: &'a [Record],
298    pub(crate) usage: InvocationUsage,
299}
300
301impl<'a, T, Record> InvocationOutcome<'a, T, Record> {
302    pub fn value(&self) -> &T {
303        &self.value
304    }
305
306    pub fn records(&self) -> &'a [Record] {
307        self.records
308    }
309
310    pub const fn usage(&self) -> InvocationUsage {
311        self.usage
312    }
313
314    pub const fn fuel_used(&self) -> u64 {
315        self.usage.fuel_used()
316    }
317
318    pub const fn record_count(&self) -> u32 {
319        self.usage.record_count()
320    }
321
322    pub const fn record_bytes(&self) -> u64 {
323        self.usage.record_bytes()
324    }
325
326    pub fn into_parts(self) -> (T, &'a [Record], InvocationUsage) {
327        (self.value, self.records, self.usage)
328    }
329}
330
331/// The result and usage after an invocation appends its records to your vector.
332#[derive(Debug)]
333pub struct InvocationReceipt<T> {
334    pub(crate) value: T,
335    pub(crate) usage: InvocationUsage,
336}
337
338impl<T> InvocationReceipt<T> {
339    pub fn value(&self) -> &T {
340        &self.value
341    }
342
343    pub const fn usage(&self) -> InvocationUsage {
344        self.usage
345    }
346
347    pub const fn fuel_used(&self) -> u64 {
348        self.usage.fuel_used()
349    }
350
351    pub const fn record_count(&self) -> u32 {
352        self.usage.record_count()
353    }
354
355    pub const fn record_bytes(&self) -> u64 {
356        self.usage.record_bytes()
357    }
358
359    pub fn into_parts(self) -> (T, InvocationUsage) {
360        (self.value, self.usage)
361    }
362}
363
364/// Read-only access to an invocation's deterministic input.
365///
366/// The invocation lifetime prevents a borrowed input projection from escaping:
367///
368/// ```compile_fail
369/// use rustia::{HostSchema, Input};
370///
371/// fn leak<C: HostSchema>(input: Input<'_, C>) -> &'static C::Input {
372///     input.get()
373/// }
374/// ```
375#[derive(Clone, Copy)]
376pub struct Input<'call, C>
377where
378    C: HostSchema,
379{
380    value: &'call C::Input,
381}
382
383impl<'call, C> Input<'call, C>
384where
385    C: HostSchema,
386{
387    pub fn get(&self) -> &'call C::Input {
388        self.value
389    }
390}
391
392/// Read-only access to saved application state, or "slots".
393#[derive(Clone, Copy)]
394pub struct Slots<'call, C>
395where
396    C: HostSchema,
397{
398    value: &'call C::Slots,
399}
400
401impl<'call, C> Slots<'call, C>
402where
403    C: HostSchema,
404{
405    pub fn get(&self) -> &'call C::Slots {
406        self.value
407    }
408}
409
410/// Lets a callback stage actions or events for the application.
411pub struct Effects<'call, C>
412where
413    C: HostSchema,
414{
415    host: &'call dyn HostContext<C>,
416    journal: &'call mut EffectJournal<C::Record>,
417}
418
419impl<C> Effects<'_, C>
420where
421    C: HostSchema,
422{
423    pub fn emit(&mut self, effect: C::Effect) -> Result<()> {
424        let sequence = self.journal.next_sequence()?;
425        let record = self.host.record_effect(sequence, effect);
426        let bytes = self.host.record_bytes(&record);
427        self.journal.push(record, bytes)
428    }
429}
430
431/// Lets a callback stage changes to saved application state.
432pub struct SlotWrites<'call, C>
433where
434    C: HostSchema,
435{
436    host: &'call dyn HostContext<C>,
437    journal: &'call mut EffectJournal<C::Record>,
438}
439
440impl<C> SlotWrites<'_, C>
441where
442    C: HostSchema,
443{
444    pub fn write(&mut self, write: C::SlotWrite) -> Result<()> {
445        let sequence = self.journal.next_sequence()?;
446        let record = self.host.record_slot_write(sequence, write);
447        let bytes = self.host.record_bytes(&record);
448        self.journal.push(record, bytes)
449    }
450}
451
452/// Lets a callback change application state immediately.
453///
454/// Available only to external-state and nondeterministic callbacks, which
455/// `DeterministicSim` rejects. Changes are outside the record transaction.
456pub struct HostMut<'call, C>
457where
458    C: HostSchema,
459{
460    value: &'call mut C::External,
461}
462
463impl<'call, C> HostMut<'call, C>
464where
465    C: HostSchema,
466{
467    pub fn get_mut(&mut self) -> &mut C::External {
468        self.value
469    }
470}
471
472#[derive(Clone, Copy)]
473pub(crate) struct JournalCheckpoint {
474    len: usize,
475    bytes: u64,
476}
477
478pub(crate) struct EffectJournal<Record> {
479    records: Vec<Record>,
480    bytes: u64,
481    limits: InvocationLimits,
482    hard_error: Option<VmError>,
483}
484
485impl<Record> EffectJournal<Record> {
486    fn new(records: Vec<Record>, limits: InvocationLimits) -> Self {
487        Self {
488            records,
489            bytes: 0,
490            limits,
491            hard_error: None,
492        }
493    }
494
495    fn checkpoint(&self) -> JournalCheckpoint {
496        JournalCheckpoint {
497            len: self.records.len(),
498            bytes: self.bytes,
499        }
500    }
501
502    fn rollback(&mut self, checkpoint: JournalCheckpoint) {
503        self.records.truncate(checkpoint.len);
504        self.bytes = checkpoint.bytes;
505    }
506
507    fn next_sequence(&mut self) -> Result<u32> {
508        if let Some(error) = &self.hard_error {
509            return Err(Error::from_engine(error.clone()));
510        }
511        let limit = usize::try_from(self.limits.max_records).unwrap_or(usize::MAX);
512        if self.records.len() >= limit {
513            return Err(self
514                .latch_resource_error("effect-record count", u64::from(self.limits.max_records)));
515        }
516        u32::try_from(self.records.len())
517            .map_err(|_| self.latch_resource_error("effect sequence", u64::from(u32::MAX)))
518    }
519
520    fn push(&mut self, record: Record, bytes: u64) -> Result<()> {
521        let Some(next_bytes) = self.bytes.checked_add(bytes) else {
522            return Err(
523                self.latch_resource_error("effect-record bytes", self.limits.max_record_bytes)
524            );
525        };
526        if next_bytes > self.limits.max_record_bytes {
527            return Err(
528                self.latch_resource_error("effect-record bytes", self.limits.max_record_bytes)
529            );
530        }
531        debug_assert!(self.records.len() < self.records.capacity());
532        self.records.push(record);
533        self.bytes = next_bytes;
534        Ok(())
535    }
536
537    fn latch_resource_error(&mut self, resource: &'static str, limit: u64) -> Error {
538        let error = VmError::new(VmErrorKind::HostResourceExhausted { resource, limit })
539            .without_source_location();
540        self.hard_error = Some(error.clone());
541        Error::from_engine(error)
542    }
543
544    fn latch_vm_error(&mut self, error: VmError) {
545        if self.hard_error.is_none() {
546            self.hard_error = Some(error);
547        }
548    }
549
550    fn hard_error(&self) -> Option<&VmError> {
551        self.hard_error.as_ref()
552    }
553}
554
555pub(crate) type ContextHandler<C> = Box<
556    dyn Fn(
557            &mut Vm,
558            &mut dyn HostContext<C>,
559            &mut EffectJournal<<C as HostSchema>::Record>,
560            &[RawValue],
561        ) -> rustia_vm::Result<Vec<RawValue>>
562        + Send
563        + Sync
564        + 'static,
565>;
566
567pub(crate) struct ContextHandlerEntry<C>
568where
569    C: HostSchema,
570{
571    name: String,
572    handler: ContextHandler<C>,
573}
574
575pub(crate) struct ContextHostFunction<C>
576where
577    C: HostSchema,
578{
579    pub(crate) name: String,
580    pub(crate) fuel_cost: u32,
581    pub(crate) capability: OpCapability,
582    pub(crate) parameter_count: u8,
583    pub(crate) parameter_types: Vec<&'static str>,
584    pub(crate) return_types: Vec<&'static str>,
585    pub(crate) fallible: bool,
586    pub(crate) handler: ContextHandler<C>,
587}
588
589impl<C> ContextHostFunction<C>
590where
591    C: HostSchema,
592{
593    pub(crate) fn into_op(self) -> HostFunctionOp {
594        let handler_name = self.name.clone();
595        HostFunctionOp::dispatched(
596            self.name,
597            self.fuel_cost,
598            self.capability,
599            std::sync::Arc::new(ContextHandlerEntry::<C> {
600                name: handler_name,
601                handler: self.handler,
602            }),
603        )
604        .with_signature(
605            self.parameter_count,
606            self.parameter_types,
607            self.return_types,
608            self.fallible,
609        )
610    }
611}
612
613/// A group of Rust callbacks installed under one script name.
614///
615/// Registrations persist across decision resets. Each callback declares which
616/// parts of the host context it needs, checked against the selected profile.
617///
618/// The views constrain how a callback reaches the invocation context. Safe
619/// Rust cannot stop a `'static` callback from using captured globals or
620/// interior mutability, so semantic purity remains an embedding contract.
621/// Callback-panic containment also requires `panic = "unwind"`; an aborting
622/// build terminates or traps before Rustia can translate the panic.
623pub struct HostModule<C>
624where
625    C: HostSchema,
626{
627    namespace: String,
628    functions: Vec<HostFunctionOp>,
629    // The erased handlers retain their exact schema type.
630    schema: PhantomData<fn(C) -> C>,
631}
632
633impl<C> HostModule<C>
634where
635    C: HostSchema,
636{
637    /// Starts a typed host module installed under `namespace`.
638    ///
639    /// The namespace and every function name must be non-empty and unique
640    /// within this module; installation validates the complete module before
641    /// exposing any binding to guest code.
642    pub fn new(namespace: impl Into<String>) -> Self {
643        Self {
644            namespace: namespace.into(),
645            functions: Vec::new(),
646            schema: PhantomData,
647        }
648    }
649
650    /// Returns the guest-visible namespace.
651    pub fn namespace(&self) -> &str {
652        &self.namespace
653    }
654
655    /// Adds the same callback definition accepted by `Rustia::create_function`
656    /// and `Rustia::register_function` to this persistent namespace.
657    pub fn function<F, S>(mut self, name: impl Into<String>, function: F) -> Self
658    where
659        F: crate::IntoHostFunctionDefinition<C, S>,
660    {
661        self.functions.push(
662            function
663                .into_definition(crate::function::adapter::Token)
664                .into_op(name.into()),
665        );
666        self
667    }
668
669    /// Returns the versioned policy used to charge host-call fuel.
670    pub const fn fuel_policy(&self) -> RustiaHostFuelPolicy {
671        RUSTIA_HOST_FUEL_POLICY
672    }
673
674    /// Iterates over the module's declared function metadata in install order.
675    pub fn functions(&self) -> impl Iterator<Item = RustiaHostFunctionInfo<'_>> + '_ {
676        self.functions
677            .iter()
678            .map(|function| RustiaHostFunctionInfo {
679                name: &function.name,
680                fuel_abi_version: RUSTIA_HOST_FUEL_ABI_VERSION,
681                fuel_cost: function.fuel_cost,
682                capability: crate::OpCapability::from_core(function.capability),
683                parameter_count: function.parameter_count,
684                parameter_types: &function.parameter_types,
685                return_types: &function.return_types,
686                fallible: function.fallible,
687            })
688    }
689
690    /// Adds a context-free function with [`OpCapability::Pure`].
691    ///
692    /// `function` has the ordinary shape `Fn(A, B, ...) -> R`; arguments and
693    /// returns use Rustia's normal value conversions. A `Result<R>` return is
694    /// exposed as a fallible host call.
695    pub fn pure<Func, Args, Return>(
696        self,
697        name: impl Into<String>,
698        fuel_cost: u32,
699        function: Func,
700    ) -> Self
701    where
702        Func: IntoHostFunction<Args, Return>,
703    {
704        self.function(
705            name,
706            crate::HostFunction::pure(function).fuel_cost(fuel_cost),
707        )
708    }
709
710    /// Adds a deterministic input reader.
711    ///
712    /// The closure shape is `for<'a> Fn(Input<'a, C>, A, B, ...) -> R`.
713    /// Its first argument can access only [`HostContext::input`].
714    pub fn input<Func, Args, Return>(
715        self,
716        name: impl Into<String>,
717        fuel_cost: u32,
718        function: Func,
719    ) -> Self
720    where
721        Func: IntoInputFunction<C, Args, Return>,
722    {
723        self.function(
724            name,
725            crate::HostFunction::input(function).fuel_cost(fuel_cost),
726        )
727    }
728
729    /// Adds a deterministic persistent-slot reader.
730    ///
731    /// The closure shape is `for<'a> Fn(Slots<'a, C>, A, B, ...) -> R`.
732    /// Its first argument can access only [`HostContext::slots`].
733    pub fn slot_read<Func, Args, Return>(
734        self,
735        name: impl Into<String>,
736        fuel_cost: u32,
737        function: Func,
738    ) -> Self
739    where
740        Func: IntoSlotReadFunction<C, Args, Return>,
741    {
742        self.function(
743            name,
744            crate::HostFunction::slot_read(function).fuel_cost(fuel_cost),
745        )
746    }
747
748    /// Adds a deterministic effect recorder.
749    ///
750    /// The closure shape is `for<'a> Fn(Effects<'a, C>, A, B, ...) -> R`.
751    /// Calls to [`Effects::emit`] stage ordered records in the current
752    /// invocation transaction.
753    pub fn effect<Func, Args, Return>(
754        self,
755        name: impl Into<String>,
756        fuel_cost: u32,
757        function: Func,
758    ) -> Self
759    where
760        Func: IntoEffectFunction<C, Args, Return>,
761    {
762        self.function(
763            name,
764            crate::HostFunction::effect(function).fuel_cost(fuel_cost),
765        )
766    }
767
768    /// Adds a deterministic persistent-slot write recorder.
769    ///
770    /// The closure shape is
771    /// `for<'a> Fn(SlotWrites<'a, C>, A, B, ...) -> R`. Calls to
772    /// [`SlotWrites::write`] stage ordered records; they do not mutate slots
773    /// directly.
774    pub fn slot_write<Func, Args, Return>(
775        self,
776        name: impl Into<String>,
777        fuel_cost: u32,
778        function: Func,
779    ) -> Self
780    where
781        Func: IntoSlotWriteFunction<C, Args, Return>,
782    {
783        self.function(
784            name,
785            crate::HostFunction::slot_write(function).fuel_cost(fuel_cost),
786        )
787    }
788
789    /// Adds a function that reads or mutates external host state.
790    ///
791    /// The closure shape is `for<'a> Fn(HostMut<'a, C>, A, B, ...) -> R`.
792    /// [`Profile::DeterministicSim`](crate::Profile::DeterministicSim)
793    /// rejects the entire module before installation. Mutations through
794    /// [`HostMut`] are immediate and cannot be rolled back by Rustia.
795    pub fn external<Func, Args, Return>(
796        self,
797        name: impl Into<String>,
798        fuel_cost: u32,
799        function: Func,
800    ) -> Self
801    where
802        Func: IntoExternalFunction<C, Args, Return>,
803    {
804        self.function(
805            name,
806            crate::HostFunction::external(function).fuel_cost(fuel_cost),
807        )
808    }
809
810    /// Adds a host operation explicitly classified as nondeterministic.
811    ///
812    /// It has the same `HostMut` closure shape and rollback caveat as
813    /// [`external`](Self::external), but metadata distinguishes an operation
814    /// whose effect itself is nondeterministic. Deterministic profiles reject
815    /// it before installation.
816    pub fn nondeterministic<Func, Args, Return>(
817        self,
818        name: impl Into<String>,
819        fuel_cost: u32,
820        function: Func,
821    ) -> Self
822    where
823        Func: IntoExternalFunction<C, Args, Return>,
824    {
825        self.function(
826            name,
827            crate::HostFunction::nondeterministic(function).fuel_cost(fuel_cost),
828        )
829    }
830
831    pub(crate) fn install(self, vm: &mut Vm) -> Result<()> {
832        if self.namespace.is_empty() {
833            return Err(Error::embed(
834                "typed host module namespace must not be empty".to_owned(),
835            ));
836        }
837        for (index, function) in self.functions.iter().enumerate() {
838            if function.name.is_empty() {
839                return Err(Error::embed(
840                    "typed host function name must not be empty".to_owned(),
841                ));
842            }
843            if self.functions[..index]
844                .iter()
845                .any(|prior| prior.name == function.name)
846            {
847                return Err(Error::embed(format!(
848                    "duplicate typed host function `{}` in module `{}`",
849                    function.name, self.namespace
850                )));
851            }
852        }
853        vm.install_host_module(self.namespace, self.functions)
854            .map_err(Error::from_engine)
855    }
856}
857
858pub(crate) struct TypedHostDispatcher<'call, C>
859where
860    C: HostSchema,
861{
862    context: &'call mut dyn HostContext<C>,
863    journal: EffectJournal<C::Record>,
864    savepoints: Vec<JournalCheckpoint>,
865}
866
867impl<'call, C> TypedHostDispatcher<'call, C>
868where
869    C: HostSchema,
870{
871    pub(crate) fn new(
872        context: &'call mut dyn HostContext<C>,
873        records: Vec<C::Record>,
874        limits: InvocationLimits,
875    ) -> Self {
876        Self {
877            context,
878            journal: EffectJournal::new(records, limits),
879            savepoints: Vec::new(),
880        }
881    }
882
883    fn invoke(
884        &mut self,
885        vm: &mut Vm,
886        handler: &(dyn std::any::Any + Send + Sync),
887        args: &[RawValue],
888    ) -> rustia_vm::Result<Vec<RawValue>> {
889        if let Some(error) = self.journal.hard_error() {
890            return Err(error.clone());
891        }
892        let entry = handler
893            .downcast_ref::<ContextHandlerEntry<C>>()
894            .ok_or_else(|| {
895                VmError::new(VmErrorKind::HostDispatcherUnavailable).without_source_location()
896            })?;
897        let checkpoint = self.journal.checkpoint();
898        let result = catch_unwind(AssertUnwindSafe(|| {
899            (entry.handler)(vm, self.context, &mut self.journal, args)
900        }));
901        match result {
902            Ok(Ok(values)) if self.journal.hard_error().is_none() => Ok(values),
903            Ok(result) => {
904                self.journal.rollback(checkpoint);
905                if let Some(error) = self.journal.hard_error() {
906                    Err(error.clone())
907                } else {
908                    result
909                }
910            }
911            Err(_) => {
912                self.journal.rollback(checkpoint);
913                let function = entry.name.clone();
914                let error =
915                    VmError::new(VmErrorKind::HostPanicked { function }).without_source_location();
916                self.journal.latch_vm_error(error.clone());
917                Err(error)
918            }
919        }
920    }
921
922    fn checkpoint(&self) -> JournalCheckpoint {
923        self.journal.checkpoint()
924    }
925
926    fn rollback(&mut self, checkpoint: JournalCheckpoint) {
927        self.journal.rollback(checkpoint);
928    }
929
930    fn latch_if_hard(&mut self, error: &Error) {
931        if let Error {
932            kind: crate::ErrorKind::Vm(error),
933            ..
934        } = error
935        {
936            if error.is_transaction_abort() {
937                self.journal.latch_vm_error((**error).clone().into_core());
938            }
939        }
940    }
941
942    fn hard_error(&self) -> Option<&VmError> {
943        self.journal.hard_error()
944    }
945
946    pub(crate) fn finish(self) -> (Vec<C::Record>, u64, Option<VmError>) {
947        (
948            self.journal.records,
949            self.journal.bytes,
950            self.journal.hard_error,
951        )
952    }
953}
954
955impl<C> VmHostDispatcher for TypedHostDispatcher<'_, C>
956where
957    C: HostSchema,
958{
959    fn invoke(
960        &mut self,
961        vm: &mut Vm,
962        handler: &(dyn std::any::Any + Send + Sync),
963        args: &[RawValue],
964    ) -> rustia_vm::Result<Vec<RawValue>> {
965        Self::invoke(self, vm, handler, args)
966    }
967
968    fn begin_savepoint(&mut self) -> rustia_vm::Result<()> {
969        self.savepoints
970            .try_reserve(1)
971            .map_err(|_| VmError::new(VmErrorKind::OutOfMemory).without_source_location())?;
972        self.savepoints.push(self.journal.checkpoint());
973        Ok(())
974    }
975
976    fn commit_savepoint(&mut self) {
977        self.savepoints
978            .pop()
979            .expect("host journal commit requires an active savepoint");
980    }
981
982    fn rollback_savepoint(&mut self) {
983        let checkpoint = self
984            .savepoints
985            .pop()
986            .expect("host journal rollback requires an active savepoint");
987        self.journal.rollback(checkpoint);
988    }
989}
990
991/// Runs scripts while borrowing the application's current host context.
992///
993/// Provided by [`Rustia::invoke`](crate::Rustia::invoke) for the duration of its
994/// closure. Host callbacks receive only their allowed context views, without
995/// a VM handle that would let them call back into Luau.
996pub struct Invocation<'call, C>
997where
998    C: HostSchema,
999{
1000    pub(crate) vm: &'call mut Vm,
1001    dispatcher: Option<TypedHostDispatcher<'call, C>>,
1002    execution: VmExecution,
1003    installation_transaction_active: bool,
1004    marker: PhantomData<fn(&mut C)>,
1005}
1006
1007impl<'call, C> Invocation<'call, C>
1008where
1009    C: HostSchema,
1010{
1011    pub(crate) fn new(
1012        vm: &'call mut Vm,
1013        dispatcher: TypedHostDispatcher<'call, C>,
1014        limits: InvocationLimits,
1015    ) -> Self {
1016        let fuel = vm
1017            .settings()
1018            .initial_fuel
1019            .map_or(limits.fuel, |configured| configured.min(limits.fuel));
1020        let execution = vm.begin_transactional_execution_with_fuel(Some(fuel));
1021        Self {
1022            vm,
1023            dispatcher: Some(dispatcher),
1024            execution,
1025            installation_transaction_active: false,
1026            marker: PhantomData,
1027        }
1028    }
1029
1030    /// Fuel remaining in the budget shared by every guest call in this
1031    /// invocation.
1032    pub const fn fuel_remaining(&self) -> u64 {
1033        match self.execution.fuel_remaining() {
1034            Some(fuel) => fuel,
1035            None => 0,
1036        }
1037    }
1038
1039    /// Creates a borrowed chunk builder using this invocation's shared fuel
1040    /// budget and typed host dispatcher.
1041    pub fn load<'chunk, 'source, S>(
1042        &'chunk mut self,
1043        source: &'source S,
1044    ) -> InvocationChunk<'chunk, 'call, 'source, C>
1045    where
1046        S: AsRef<[u8]> + ?Sized,
1047    {
1048        InvocationChunk::new(self, source.as_ref())
1049    }
1050
1051    pub(crate) fn scoped<T>(
1052        &mut self,
1053        operation: impl FnOnce(&mut Self) -> Result<T>,
1054    ) -> Result<T> {
1055        let checkpoint = self
1056            .dispatcher
1057            .as_ref()
1058            .expect("invocation dispatcher is available")
1059            .checkpoint();
1060        let result = operation(self);
1061        match result {
1062            Ok(value)
1063                if self
1064                    .dispatcher
1065                    .as_ref()
1066                    .expect("invocation dispatcher is available")
1067                    .hard_error()
1068                    .is_none() =>
1069            {
1070                Ok(value)
1071            }
1072            Ok(_) => {
1073                self.dispatcher
1074                    .as_mut()
1075                    .expect("invocation dispatcher is available")
1076                    .rollback(checkpoint);
1077                Err(Error::from_engine(
1078                    self.dispatcher
1079                        .as_ref()
1080                        .expect("invocation dispatcher is available")
1081                        .hard_error()
1082                        .expect("checked above")
1083                        .clone(),
1084                ))
1085            }
1086            Err(error) => {
1087                let dispatcher = self
1088                    .dispatcher
1089                    .as_mut()
1090                    .expect("invocation dispatcher is available");
1091                dispatcher.rollback(checkpoint);
1092                dispatcher.latch_if_hard(&error);
1093                if let Some(hard_error) = dispatcher.hard_error() {
1094                    Err(Error::from_engine(hard_error.clone()))
1095                } else {
1096                    Err(error)
1097                }
1098            }
1099        }
1100    }
1101
1102    pub(crate) fn call_retained_raw(
1103        &mut self,
1104        function: RawValue,
1105        args: &[RawValue],
1106    ) -> Result<Vec<RawValue>> {
1107        let vm = &mut *self.vm;
1108        let execution = &mut self.execution;
1109        let dispatcher = self
1110            .dispatcher
1111            .as_mut()
1112            .expect("invocation dispatcher is available");
1113        vm.call_retained_function_in(function, args, execution, dispatcher)
1114            .map_err(Error::from_engine)
1115    }
1116
1117    pub fn install(&mut self, module: &CompiledModule) -> Result<Exports> {
1118        self.install_with_environment(module, None)
1119    }
1120
1121    fn install_with_environment(
1122        &mut self,
1123        module: &CompiledModule,
1124        environment: Option<RawValue>,
1125    ) -> Result<Exports> {
1126        self.scoped(|invocation| {
1127            let started_outer = !invocation.installation_transaction_active;
1128            if started_outer {
1129                invocation
1130                    .vm
1131                    .begin_guest_transaction()
1132                    .map_err(Error::from_engine)?;
1133                invocation.installation_transaction_active = true;
1134            }
1135            if let Err(error) = invocation.vm.begin_guest_transaction() {
1136                if started_outer {
1137                    invocation.vm.rollback_guest_transaction();
1138                    invocation.installation_transaction_active = false;
1139                }
1140                return Err(Error::from_engine(error));
1141            }
1142            let vm = &mut *invocation.vm;
1143            let execution = &mut invocation.execution;
1144            let dispatcher = invocation
1145                .dispatcher
1146                .as_mut()
1147                .expect("invocation dispatcher is available");
1148            let outcome: Result<Exports> = (|| {
1149                let module_cohort = vm.create_module_cohort().map_err(Error::from_engine)?;
1150                let environment = match environment {
1151                    Some(environment) => environment,
1152                    None => vm.create_module_environment().map_err(Error::from_engine)?,
1153                };
1154                let value = vm
1155                    .run_installation_in_environment(
1156                        &module.program,
1157                        environment,
1158                        module_cohort,
1159                        execution,
1160                        dispatcher,
1161                    )
1162                    .map_err(Error::from_engine)?;
1163                let value = vm.retain_value(value).map_err(Error::from_engine)?;
1164                Ok(Exports::new(value, vm.decision_epoch()))
1165            })();
1166            match outcome {
1167                Ok(exports) => {
1168                    if let Err(error) = vm.commit_guest_transaction() {
1169                        vm.rollback_guest_transaction();
1170                        if started_outer {
1171                            vm.rollback_guest_transaction();
1172                            invocation.installation_transaction_active = false;
1173                        }
1174                        Err(Error::from_engine(error).installation_rolled_back())
1175                    } else {
1176                        Ok(exports)
1177                    }
1178                }
1179                Err(error) => {
1180                    vm.rollback_guest_transaction();
1181                    if started_outer {
1182                        vm.rollback_guest_transaction();
1183                        invocation.installation_transaction_active = false;
1184                    }
1185                    Err(error.installation_rolled_back())
1186                }
1187            }
1188        })
1189    }
1190
1191    /// Executes a precompiled stateless decision body directly.
1192    ///
1193    /// Unlike [`install`](Self::install), this does not construct an exports
1194    /// table, retain bytecode in the VM, or return handles that survive the
1195    /// invocation. Host effects and slot writes remain transactional under the
1196    /// surrounding invocation.
1197    pub fn call_entry<Return>(&mut self, entry: &CompiledEntry) -> Result<Return>
1198    where
1199        Return: FromRustia,
1200    {
1201        self.scoped(|invocation| {
1202            let value = {
1203                let Self {
1204                    vm,
1205                    dispatcher,
1206                    execution,
1207                    ..
1208                } = invocation;
1209                let dispatcher = dispatcher
1210                    .as_mut()
1211                    .expect("invocation dispatcher is available");
1212                vm.run_hardened_leaf_entry_in(&entry.program, execution, dispatcher)
1213                    .map_err(Error::from_engine)?
1214            };
1215            let value = snapshot_value(invocation.vm, value)?;
1216            Return::from_rustia(value)
1217        })
1218    }
1219
1220    pub(crate) fn convert_call<Args, Return>(
1221        &mut self,
1222        function: RawValue,
1223        args: Args,
1224    ) -> Result<Return>
1225    where
1226        Args: IntoRustiaMulti,
1227        Return: FromRustiaMulti,
1228    {
1229        self.scoped(|invocation| {
1230            let owned_args = args.into_rustia_multi()?;
1231            let (raw_args, _argument_roots) = load_owned_arguments(invocation.vm, &owned_args)?;
1232            let raw_results = invocation.call_retained_raw(function, &raw_args)?;
1233            let results = raw_results
1234                .into_iter()
1235                .map(|value| snapshot_value(invocation.vm, value))
1236                .collect::<Result<Vec<_>>>()?;
1237            Return::from_rustia_multi(results)
1238        })
1239    }
1240
1241    pub(crate) fn finish(
1242        mut self,
1243        commit_installation: bool,
1244    ) -> (TypedHostDispatcher<'call, C>, u64) {
1245        if self.installation_transaction_active {
1246            if commit_installation {
1247                self.vm
1248                    .commit_guest_transaction()
1249                    .expect("outer installation transaction has no parent journal");
1250            } else {
1251                self.vm.rollback_guest_transaction();
1252            }
1253            self.installation_transaction_active = false;
1254        }
1255        let dispatcher = self
1256            .dispatcher
1257            .take()
1258            .expect("invocation dispatcher is available");
1259        (dispatcher, self.execution.fuel_used())
1260    }
1261
1262    pub(crate) fn can_commit_installation(&self) -> bool {
1263        self.dispatcher
1264            .as_ref()
1265            .expect("invocation dispatcher is available")
1266            .hard_error()
1267            .is_none()
1268    }
1269}
1270
1271/// A borrowed source chunk executed through a typed [`Invocation`].
1272#[must_use = "an invocation chunk does nothing until eval, eval_live, eval_serde, exec, or install is called"]
1273pub struct InvocationChunk<'chunk, 'call, 'source, C>
1274where
1275    C: HostSchema,
1276{
1277    invocation: &'chunk mut Invocation<'call, C>,
1278    source: &'source [u8],
1279    source_name: Option<String>,
1280    source_map: crate::SourceMap,
1281    environment: Option<Table>,
1282}
1283
1284impl<'chunk, 'call, 'source, C> InvocationChunk<'chunk, 'call, 'source, C>
1285where
1286    C: HostSchema,
1287{
1288    fn new(invocation: &'chunk mut Invocation<'call, C>, source: &'source [u8]) -> Self {
1289        Self {
1290            invocation,
1291            source,
1292            source_name: None,
1293            source_map: crate::SourceMap::default(),
1294            environment: None,
1295        }
1296    }
1297
1298    /// Sets the source name used by compile/runtime diagnostics and as the
1299    /// referrer passed to the host module resolver for `require` calls.
1300    pub fn source_name(mut self, source_name: impl Into<String>) -> Self {
1301        self.source_name = Some(source_name.into());
1302        self
1303    }
1304
1305    /// Maps a generated console prefix out of human-facing diagnostics.
1306    pub fn source_map(mut self, mapping: crate::SourceMap) -> Self {
1307        self.source_map = mapping;
1308        self
1309    }
1310
1311    /// Selects the exact rooted lexical environment.
1312    pub fn environment(mut self, environment: impl Into<Table>) -> Self {
1313        self.environment = Some(environment.into());
1314        self
1315    }
1316
1317    /// Evaluates and converts the first result through the owned typed facade.
1318    pub fn eval<T>(self) -> Result<T>
1319    where
1320        T: FromRustia,
1321    {
1322        self.execute(|invocation, value| {
1323            let value = snapshot_value(invocation.vm, value)?;
1324            T::from_rustia(value)
1325        })
1326    }
1327
1328    /// Evaluates and retains the first result without snapshotting.
1329    pub fn eval_live(self) -> Result<Value> {
1330        self.execute(|invocation, value| Value::retain(invocation.vm, value))
1331    }
1332
1333    /// Evaluates and deserializes directly from the live VM graph.
1334    pub fn eval_serde<T>(self) -> Result<T>
1335    where
1336        T: serde::de::DeserializeOwned,
1337    {
1338        self.execute(|invocation, value| from_live(invocation.vm, value))
1339    }
1340
1341    /// Executes the chunk for side effects.
1342    pub fn exec(self) -> Result<()> {
1343        self.execute(|_, _| Ok(()))
1344    }
1345
1346    /// Atomically installs the chunk. The result remains provisional until
1347    /// the enclosing typed invocation commits its record transaction.
1348    pub fn install(self) -> Result<Exports> {
1349        let (invocation, module, environment) = self.prepare()?;
1350        let raw_environment = environment
1351            .as_ref()
1352            .map(|environment| environment.raw(invocation.vm, "chunk environment handle"))
1353            .transpose()?;
1354        invocation.install_with_environment(&module, raw_environment)
1355    }
1356
1357    fn execute<T>(
1358        self,
1359        convert: impl FnOnce(&mut Invocation<'call, C>, RawValue) -> Result<T>,
1360    ) -> Result<T> {
1361        let (invocation, module, environment) = self.prepare()?;
1362        let raw_environment = environment
1363            .as_ref()
1364            .map(|environment| environment.raw(invocation.vm, "chunk environment handle"))
1365            .transpose()?;
1366        invocation.scoped(|invocation| {
1367            let value = {
1368                let vm = &mut *invocation.vm;
1369                let execution = &mut invocation.execution;
1370                let dispatcher = invocation
1371                    .dispatcher
1372                    .as_mut()
1373                    .expect("invocation dispatcher is available");
1374                match raw_environment {
1375                    Some(environment) => vm
1376                        .run_in_environment(&module.program, environment, execution, dispatcher)
1377                        .map_err(Error::from_engine),
1378                    None => vm
1379                        .run_in(&module.program, execution, dispatcher)
1380                        .map_err(Error::from_engine),
1381                }?
1382            };
1383            convert(invocation, value).map_err(|error| {
1384                error.with_result_source(
1385                    module.program.source_name.as_deref().unwrap_or("chunk"),
1386                    crate::DiagnosticLimits::from_core(invocation.vm.settings().diagnostic_limits),
1387                )
1388            })
1389        })
1390    }
1391
1392    fn prepare(
1393        self,
1394    ) -> Result<(
1395        &'chunk mut Invocation<'call, C>,
1396        CompiledModule,
1397        Option<Table>,
1398    )> {
1399        let Self {
1400            invocation,
1401            source,
1402            source_name,
1403            source_map,
1404            environment,
1405        } = self;
1406        if invocation.vm.settings().guest_surface.is_hardened_leaf() {
1407            return Err(Error::from_engine(
1408                VmError::new(VmErrorKind::HardenedLeafViolation {
1409                    feature: "dynamic source loading",
1410                })
1411                .without_source_location(),
1412            ));
1413        }
1414        environment
1415            .as_ref()
1416            .map(|environment| environment.raw(invocation.vm, "chunk environment handle"))
1417            .transpose()?;
1418        source_map.validate(source)?;
1419        let limits = crate::DiagnosticLimits::from_core(invocation.vm.settings().diagnostic_limits);
1420        let mut module = crate::Rustia::compile_module_bytes_with_constructor_order(
1421            source_name.unwrap_or_else(|| "chunk".to_owned()),
1422            source,
1423            invocation.vm.profile() == rustia_vm::Profile::Puc51Compat,
1424            crate::DiagnosticLimits::from_core(invocation.vm.settings().diagnostic_limits),
1425        )
1426        .map_err(|error| {
1427            source_map
1428                .apply_error(error, source, limits)
1429                .admit_diagnostic(invocation.vm)
1430        })?;
1431        source_map.apply(&mut module, source, limits);
1432        Ok((invocation, module, environment))
1433    }
1434}
1435
1436impl<C> std::fmt::Debug for InvocationChunk<'_, '_, '_, C>
1437where
1438    C: HostSchema,
1439{
1440    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1441        formatter
1442            .debug_struct("InvocationChunk")
1443            .field("source_bytes", &self.source.len())
1444            .field("source_name", &self.source_name)
1445            .field("has_environment", &self.environment.is_some())
1446            .finish_non_exhaustive()
1447    }
1448}
1449
1450impl<C> Drop for Invocation<'_, C>
1451where
1452    C: HostSchema,
1453{
1454    fn drop(&mut self) {
1455        if self.installation_transaction_active {
1456            self.vm.rollback_guest_transaction();
1457            self.installation_transaction_active = false;
1458        }
1459    }
1460}
1461
1462pub(crate) mod adapter {
1463    use super::*;
1464    use crate::function::adapter::Token;
1465
1466    pub(crate) trait Input<C: HostSchema, Args, Return> {
1467        fn into_input_function(
1468            self,
1469            token: Token,
1470            name: String,
1471            fuel_cost: u32,
1472        ) -> ContextHostFunction<C>;
1473    }
1474
1475    pub(crate) trait SlotRead<C: HostSchema, Args, Return> {
1476        fn into_slot_read_function(
1477            self,
1478            token: Token,
1479            name: String,
1480            fuel_cost: u32,
1481        ) -> ContextHostFunction<C>;
1482    }
1483
1484    pub(crate) trait Effect<C: HostSchema, Args, Return> {
1485        fn into_effect_function(
1486            self,
1487            token: Token,
1488            name: String,
1489            fuel_cost: u32,
1490        ) -> ContextHostFunction<C>;
1491    }
1492
1493    pub(crate) trait SlotWrite<C: HostSchema, Args, Return> {
1494        fn into_slot_write_function(
1495            self,
1496            token: Token,
1497            name: String,
1498            fuel_cost: u32,
1499        ) -> ContextHostFunction<C>;
1500    }
1501
1502    pub(crate) trait External<C: HostSchema, Args, Return> {
1503        fn into_external_function(
1504            self,
1505            token: Token,
1506            name: String,
1507            fuel_cost: u32,
1508            capability: OpCapability,
1509        ) -> ContextHostFunction<C>;
1510    }
1511}
1512
1513/// A callback accepted by [`crate::HostFunction::input`].
1514///
1515/// Implemented automatically for matching closures and function pointers.
1516/// This sealed trait can be used as a generic bound.
1517#[allow(private_bounds)]
1518pub trait IntoInputFunction<C, Args, Return>:
1519    adapter::Input<C, Args, Return> + Send + Sync + 'static
1520where
1521    C: HostSchema,
1522{
1523}
1524
1525impl<C: HostSchema, Args, Return, F> IntoInputFunction<C, Args, Return> for F where
1526    F: adapter::Input<C, Args, Return> + Send + Sync + 'static
1527{
1528}
1529
1530/// A callback accepted by [`crate::HostFunction::slot_read`].
1531///
1532/// Implemented automatically for matching closures and function pointers.
1533/// This sealed trait can be used as a generic bound.
1534#[allow(private_bounds)]
1535pub trait IntoSlotReadFunction<C, Args, Return>:
1536    adapter::SlotRead<C, Args, Return> + Send + Sync + 'static
1537where
1538    C: HostSchema,
1539{
1540}
1541
1542impl<C: HostSchema, Args, Return, F> IntoSlotReadFunction<C, Args, Return> for F where
1543    F: adapter::SlotRead<C, Args, Return> + Send + Sync + 'static
1544{
1545}
1546
1547/// A callback accepted by [`crate::HostFunction::effect`].
1548///
1549/// Implemented automatically for matching closures and function pointers.
1550/// This sealed trait can be used as a generic bound.
1551#[allow(private_bounds)]
1552pub trait IntoEffectFunction<C, Args, Return>:
1553    adapter::Effect<C, Args, Return> + Send + Sync + 'static
1554where
1555    C: HostSchema,
1556{
1557}
1558
1559impl<C: HostSchema, Args, Return, F> IntoEffectFunction<C, Args, Return> for F where
1560    F: adapter::Effect<C, Args, Return> + Send + Sync + 'static
1561{
1562}
1563
1564/// A callback accepted by [`crate::HostFunction::slot_write`].
1565///
1566/// Implemented automatically for matching closures and function pointers.
1567/// This sealed trait can be used as a generic bound.
1568#[allow(private_bounds)]
1569pub trait IntoSlotWriteFunction<C, Args, Return>:
1570    adapter::SlotWrite<C, Args, Return> + Send + Sync + 'static
1571where
1572    C: HostSchema,
1573{
1574}
1575
1576impl<C: HostSchema, Args, Return, F> IntoSlotWriteFunction<C, Args, Return> for F where
1577    F: adapter::SlotWrite<C, Args, Return> + Send + Sync + 'static
1578{
1579}
1580
1581/// A callback accepted by [`crate::HostFunction::external`] or
1582/// [`crate::HostFunction::nondeterministic`].
1583///
1584/// Implemented automatically for matching closures and function pointers.
1585/// This sealed trait can be used as a generic bound.
1586#[allow(private_bounds)]
1587pub trait IntoExternalFunction<C, Args, Return>:
1588    adapter::External<C, Args, Return> + Send + Sync + 'static
1589where
1590    C: HostSchema,
1591{
1592}
1593
1594impl<C: HostSchema, Args, Return, F> IntoExternalFunction<C, Args, Return> for F where
1595    F: adapter::External<C, Args, Return> + Send + Sync + 'static
1596{
1597}
1598
1599pub(crate) trait MakeCapabilityView<C>
1600where
1601    C: HostSchema,
1602{
1603    type View<'call>
1604    where
1605        C: 'call;
1606
1607    fn make<'call>(
1608        context: &'call mut dyn HostContext<C>,
1609        journal: &'call mut EffectJournal<C::Record>,
1610    ) -> Self::View<'call>;
1611}
1612
1613pub(crate) struct InputView;
1614pub(crate) struct SlotReadView;
1615pub(crate) struct EffectView;
1616pub(crate) struct SlotWriteView;
1617pub(crate) struct ExternalView;
1618
1619impl<C: HostSchema> MakeCapabilityView<C> for ExternalView {
1620    type View<'call>
1621        = HostMut<'call, C>
1622    where
1623        C: 'call;
1624
1625    fn make<'call>(
1626        context: &'call mut dyn HostContext<C>,
1627        _journal: &'call mut EffectJournal<C::Record>,
1628    ) -> Self::View<'call> {
1629        HostMut {
1630            value: context.external_mut(),
1631        }
1632    }
1633}
1634
1635impl<C> MakeCapabilityView<C> for InputView
1636where
1637    C: HostSchema,
1638{
1639    type View<'call>
1640        = Input<'call, C>
1641    where
1642        C: 'call;
1643
1644    fn make<'call>(
1645        context: &'call mut dyn HostContext<C>,
1646        _journal: &'call mut EffectJournal<C::Record>,
1647    ) -> Self::View<'call> {
1648        Input {
1649            value: context.input(),
1650        }
1651    }
1652}
1653
1654impl<C> MakeCapabilityView<C> for SlotReadView
1655where
1656    C: HostSchema,
1657{
1658    type View<'call>
1659        = Slots<'call, C>
1660    where
1661        C: 'call;
1662
1663    fn make<'call>(
1664        context: &'call mut dyn HostContext<C>,
1665        _journal: &'call mut EffectJournal<C::Record>,
1666    ) -> Self::View<'call> {
1667        Slots {
1668            value: context.slots(),
1669        }
1670    }
1671}
1672
1673impl<C> MakeCapabilityView<C> for EffectView
1674where
1675    C: HostSchema,
1676{
1677    type View<'call>
1678        = Effects<'call, C>
1679    where
1680        C: 'call;
1681
1682    fn make<'call>(
1683        context: &'call mut dyn HostContext<C>,
1684        journal: &'call mut EffectJournal<C::Record>,
1685    ) -> Self::View<'call> {
1686        Effects {
1687            host: &*context,
1688            journal,
1689        }
1690    }
1691}
1692
1693impl<C> MakeCapabilityView<C> for SlotWriteView
1694where
1695    C: HostSchema,
1696{
1697    type View<'call>
1698        = SlotWrites<'call, C>
1699    where
1700        C: 'call;
1701
1702    fn make<'call>(
1703        context: &'call mut dyn HostContext<C>,
1704        journal: &'call mut EffectJournal<C::Record>,
1705    ) -> Self::View<'call> {
1706        SlotWrites {
1707            host: &*context,
1708            journal,
1709        }
1710    }
1711}
1712
1713macro_rules! context_function {
1714    (
1715        $trait_name:ident,
1716        $sealed_trait:ident,
1717        $method_name:ident,
1718        $view:ident,
1719        $capability:expr,
1720        $view_factory:ty
1721    ) => {
1722        impl<C, Func, Return> adapter::$sealed_trait<C, (), Return> for Func
1723        where
1724            C: HostSchema,
1725            Func: for<'call> Fn($view<'call, C>) -> Return + Send + Sync + 'static,
1726            Return: IntoHostReturn,
1727        {
1728            fn $method_name(self, _token: crate::function::adapter::Token, name: String, fuel_cost: u32) -> ContextHostFunction<C> {
1729                let diagnostic_name = name.clone();
1730                ContextHostFunction {
1731                    name,
1732                    fuel_cost,
1733                    capability: $capability,
1734                    parameter_count: 0,
1735                    parameter_types: Vec::new(),
1736                    return_types: Return::rustia_type_names(crate::function::adapter::Token),
1737                    fallible: Return::is_fallible(crate::function::adapter::Token),
1738                    handler: Box::new(move |vm, context, journal, _args| {
1739                        let view =
1740                            <$view_factory as MakeCapabilityView<C>>::make(context, journal);
1741                        host_return_to_raw(vm, &diagnostic_name, self(view))
1742                    }),
1743                }
1744            }
1745        }
1746
1747        context_function!(
1748            @arity $trait_name,
1749            $sealed_trait,
1750            $method_name,
1751            $view,
1752            $capability,
1753            $view_factory;
1754            1;
1755            A
1756        );
1757        context_function!(
1758            @arity $trait_name,
1759            $sealed_trait,
1760            $method_name,
1761            $view,
1762            $capability,
1763            $view_factory;
1764            2;
1765            A,
1766            B
1767        );
1768        context_function!(
1769            @arity $trait_name,
1770            $sealed_trait,
1771            $method_name,
1772            $view,
1773            $capability,
1774            $view_factory;
1775            3;
1776            A,
1777            B,
1778            D
1779        );
1780        context_function!(
1781            @arity $trait_name,
1782            $sealed_trait,
1783            $method_name,
1784            $view,
1785            $capability,
1786            $view_factory;
1787            4;
1788            A,
1789            B,
1790            D,
1791            E
1792        );
1793        context_function!(
1794            @arity $trait_name,
1795            $sealed_trait,
1796            $method_name,
1797            $view,
1798            $capability,
1799            $view_factory;
1800            5;
1801            A,
1802            B,
1803            D,
1804            E,
1805            F
1806        );
1807        context_function!(
1808            @arity $trait_name,
1809            $sealed_trait,
1810            $method_name,
1811            $view,
1812            $capability,
1813            $view_factory;
1814            6;
1815            A,
1816            B,
1817            D,
1818            E,
1819            F,
1820            G
1821        );
1822        context_function!(
1823            @arity $trait_name,
1824            $sealed_trait,
1825            $method_name,
1826            $view,
1827            $capability,
1828            $view_factory;
1829            7;
1830            A,
1831            B,
1832            D,
1833            E,
1834            F,
1835            G,
1836            H
1837        );
1838        context_function!(
1839            @arity $trait_name,
1840            $sealed_trait,
1841            $method_name,
1842            $view,
1843            $capability,
1844            $view_factory;
1845            8;
1846            A,
1847            B,
1848            D,
1849            E,
1850            F,
1851            G,
1852            H,
1853            I
1854        );
1855    };
1856    (
1857        @arity $trait_name:ident,
1858        $sealed_trait:ident,
1859        $method_name:ident,
1860        $view:ident,
1861        $capability:expr,
1862        $view_factory:ty;
1863        $parameter_count:expr;
1864        $($name:ident),+
1865    ) => {
1866        impl<C, Func, Return, $($name),+> adapter::$sealed_trait<C, ($($name,)+), Return> for Func
1867        where
1868            C: HostSchema,
1869            Func: for<'call> Fn($view<'call, C>, $($name),+) -> Return
1870                + Send
1871                + Sync
1872                + 'static,
1873            Return: IntoHostReturn,
1874            $($name: FromHostArgument,)+
1875        {
1876            #[allow(non_snake_case)]
1877            fn $method_name(self, _token: crate::function::adapter::Token, name: String, fuel_cost: u32) -> ContextHostFunction<C> {
1878                let diagnostic_name = name.clone();
1879                ContextHostFunction {
1880                    name,
1881                    fuel_cost,
1882                    capability: $capability,
1883                    parameter_count: $parameter_count,
1884                    parameter_types: vec![$(type_name::<$name>()),+],
1885                    return_types: Return::rustia_type_names(crate::function::adapter::Token),
1886                    fallible: Return::is_fallible(crate::function::adapter::Token),
1887                    handler: Box::new(move |vm, context, journal, args| {
1888                        let mut index = 0usize;
1889                        $(
1890                            let $name =
1891                                host_arg_from_raw(vm, args, index, &diagnostic_name)?;
1892                            index += 1;
1893                        )+
1894                        let _ = index;
1895                        let view =
1896                            <$view_factory as MakeCapabilityView<C>>::make(context, journal);
1897                        host_return_to_raw(vm, &diagnostic_name, self(view, $($name),+))
1898                    }),
1899                }
1900            }
1901        }
1902    };
1903}
1904
1905context_function!(
1906    IntoInputFunction,
1907    Input,
1908    into_input_function,
1909    Input,
1910    OpCapability::ReadsDeterministicInput,
1911    InputView
1912);
1913context_function!(
1914    IntoSlotReadFunction,
1915    SlotRead,
1916    into_slot_read_function,
1917    Slots,
1918    OpCapability::ReadsSlotState,
1919    SlotReadView
1920);
1921context_function!(
1922    IntoEffectFunction,
1923    Effect,
1924    into_effect_function,
1925    Effects,
1926    OpCapability::EmitsDeterministicEffect,
1927    EffectView
1928);
1929context_function!(
1930    IntoSlotWriteFunction,
1931    SlotWrite,
1932    into_slot_write_function,
1933    SlotWrites,
1934    OpCapability::WritesSlotEffect,
1935    SlotWriteView
1936);
1937
1938macro_rules! external_function {
1939    ($parameter_count:expr; $($name:ident),* $(,)?) => {
1940        impl<C, Func, Return, $($name),*> adapter::External<C, ($($name,)*), Return> for Func
1941        where
1942            C: HostSchema,
1943            Func: for<'call> Fn(HostMut<'call, C>, $($name),*) -> Return
1944                + Send
1945                + Sync
1946                + 'static,
1947            Return: IntoHostReturn,
1948            $($name: FromHostArgument,)*
1949        {
1950            #[allow(non_snake_case, unused_mut, unused_variables)]
1951            fn into_external_function(
1952                self,
1953                _token: crate::function::adapter::Token,
1954                name: String,
1955                fuel_cost: u32,
1956                capability: OpCapability,
1957            ) -> ContextHostFunction<C> {
1958                let diagnostic_name = name.clone();
1959                ContextHostFunction {
1960                    name,
1961                    fuel_cost,
1962                    capability,
1963                    parameter_count: $parameter_count,
1964                    parameter_types: vec![$(type_name::<$name>()),*],
1965                    return_types: Return::rustia_type_names(crate::function::adapter::Token),
1966                    fallible: Return::is_fallible(crate::function::adapter::Token),
1967                    handler: Box::new(move |vm, context, _journal, args| {
1968                        let mut index = 0usize;
1969                        $(
1970                            let $name =
1971                                host_arg_from_raw(vm, args, index, &diagnostic_name)?;
1972                            index += 1;
1973                        )*
1974                        let _ = index;
1975                        host_return_to_raw(
1976                            vm,
1977                            &diagnostic_name,
1978                            self(
1979                                HostMut {
1980                                    value: context.external_mut(),
1981                                },
1982                                $($name),*
1983                            ),
1984                        )
1985                    }),
1986                }
1987            }
1988        }
1989    };
1990}
1991
1992external_function!(0;);
1993external_function!(1; A);
1994external_function!(2; A, B);
1995external_function!(3; A, B, D);
1996external_function!(4; A, B, D, E);
1997external_function!(5; A, B, D, E, F);
1998external_function!(6; A, B, D, E, F, G);
1999external_function!(7; A, B, D, E, F, G, H);
2000external_function!(8; A, B, D, E, F, G, H, I);