rustia/host_function.rs
1//! Shared synchronous callback definitions for live values and persistent configuration.
2
3use crate::function::{adapter::Token, IntoHostFunction};
4use crate::invocation::{
5 IntoEffectFunction, IntoExternalFunction, IntoInputFunction, IntoSlotReadFunction,
6 IntoSlotWriteFunction,
7};
8use crate::{Error, Function, HostSchema, OpCapability, Result, Rustia, VmError, VmErrorKind};
9use rustia_vm::HostFunctionOp;
10use std::marker::PhantomData;
11
12/// A Rust callback and its declared capabilities and fuel cost.
13///
14/// Pass it to [`Rustia::create_function`] to create a live function, or to
15/// [`Rustia::register_function`] to keep the registration across decision resets.
16/// It can also be added to a [`crate::HostModule`]. Plain closures work for
17/// simple callbacks; use this type to choose capabilities or change the default
18/// cost of one fuel unit per call.
19///
20/// ```
21/// use rustia::{HostFunction, Rustia};
22///
23/// let mut lua = Rustia::builder().build()?;
24/// lua.register_function("double", HostFunction::pure(|n: i64| n * 2).fuel_cost(2))?;
25/// assert_eq!(lua.load("return double(21)").eval::<i64>()?, 42);
26/// # Ok::<(), rustia::Error>(())
27/// ```
28///
29/// Arguments and tuple results through arity eight can mix ordinary Rust data
30/// with live [`crate::Value`], [`crate::Table`], and [`Function`] handles. Calls
31/// are synchronous and receive no VM borrow, so they cannot call back into Luau.
32/// A callback can return [`Result`] to report a failure.
33///
34/// Closures must be `Send + Sync + 'static`; use the capability-specific
35/// constructors to borrow per-invocation host state. Captured allocations are
36/// outside the VM memory limit. Captured state must honor the declared capability,
37/// and captured destructors must not panic. In unwinding builds, a callback panic
38/// is caught and blocks further guest execution until [`Rustia::reset_decision`];
39/// in aborting builds, it terminates or traps instead.
40pub struct HostFunction<C: HostSchema = ()> {
41 build: Box<dyn FnOnce(String, u32) -> HostFunctionOp + Send + Sync>,
42 fuel_cost: u32,
43 // The erased dispatcher captures this exact schema's TypeId.
44 schema: PhantomData<fn(C) -> C>,
45}
46
47impl<C: HostSchema> HostFunction<C> {
48 fn from_factory(
49 build: impl FnOnce(String, u32) -> HostFunctionOp + Send + Sync + 'static,
50 ) -> Self {
51 Self {
52 build: Box::new(build),
53 fuel_cost: 1,
54 schema: PhantomData,
55 }
56 }
57
58 /// Declares a callback that neither reads nor changes external mutable state.
59 ///
60 /// Rustia trusts this declaration; it cannot inspect the closure's captures.
61 pub fn pure<F, A, R>(function: F) -> Self
62 where
63 F: IntoHostFunction<A, R>,
64 {
65 Self::with_capability(OpCapability::Pure, function)
66 }
67
68 /// Declares the capability used by a callback's captured state.
69 ///
70 /// For a typed host schema, prefer constructors such as [`input`](Self::input)
71 /// and [`effect`](Self::effect), which provide the appropriate borrowed view.
72 pub fn with_capability<F, A, R>(capability: OpCapability, function: F) -> Self
73 where
74 F: IntoHostFunction<A, R>,
75 {
76 Self::from_factory(move |name, fuel| {
77 function.into_host_function(Token, name, fuel, capability.to_core())
78 })
79 }
80
81 /// Creates a callback that borrows the invocation's deterministic input.
82 pub fn input<F, A, R>(function: F) -> Self
83 where
84 F: IntoInputFunction<C, A, R>,
85 {
86 Self::from_factory(move |name, fuel| {
87 function.into_input_function(Token, name, fuel).into_op()
88 })
89 }
90
91 /// Creates a callback that borrows the invocation's deterministic slot state.
92 pub fn slot_read<F, A, R>(function: F) -> Self
93 where
94 F: IntoSlotReadFunction<C, A, R>,
95 {
96 Self::from_factory(move |name, fuel| {
97 function
98 .into_slot_read_function(Token, name, fuel)
99 .into_op()
100 })
101 }
102
103 /// Creates a callback that stages effects in the invocation's record journal.
104 pub fn effect<F, A, R>(function: F) -> Self
105 where
106 F: IntoEffectFunction<C, A, R>,
107 {
108 Self::from_factory(move |name, fuel| {
109 function.into_effect_function(Token, name, fuel).into_op()
110 })
111 }
112
113 /// Creates a callback that stages slot writes in the invocation's record journal.
114 pub fn slot_write<F, A, R>(function: F) -> Self
115 where
116 F: IntoSlotWriteFunction<C, A, R>,
117 {
118 Self::from_factory(move |name, fuel| {
119 function
120 .into_slot_write_function(Token, name, fuel)
121 .into_op()
122 })
123 }
124
125 /// An external-state callback, rejected by deterministic profiles.
126 pub fn external<F, A, R>(function: F) -> Self
127 where
128 F: IntoExternalFunction<C, A, R>,
129 {
130 Self::from_factory(move |name, fuel| {
131 function
132 .into_external_function(
133 Token,
134 name,
135 fuel,
136 OpCapability::ReadsExternalMutableState.to_core(),
137 )
138 .into_op()
139 })
140 }
141
142 /// A nondeterministic callback, rejected by deterministic profiles.
143 pub fn nondeterministic<F, A, R>(function: F) -> Self
144 where
145 F: IntoExternalFunction<C, A, R>,
146 {
147 Self::from_factory(move |name, fuel| {
148 function
149 .into_external_function(
150 Token,
151 name,
152 fuel,
153 OpCapability::NondeterministicEffect.to_core(),
154 )
155 .into_op()
156 })
157 }
158
159 /// Sets the fuel charged for each call. The default is one; zero is rejected
160 /// when the function is created or registered.
161 pub fn fuel_cost(mut self, fuel_cost: u32) -> Self {
162 self.fuel_cost = fuel_cost;
163 self
164 }
165
166 pub(crate) fn into_op(self, name: String) -> HostFunctionOp {
167 (self.build)(name, self.fuel_cost)
168 }
169}
170
171mod adapter {
172 use super::*;
173
174 pub(crate) trait Definition<C: HostSchema, Signature> {
175 fn into_definition(self, token: Token) -> HostFunction<C>;
176 }
177}
178
179/// A plain callback or configured [`HostFunction`] accepted by Rustia.
180///
181/// This sealed trait can be used as a generic bound. Closures and function
182/// pointers implement it automatically when their arguments and results are
183/// supported by Rustia's callback conversions.
184///
185/// ```compile_fail
186/// struct CustomDefinition;
187/// impl rustia::IntoHostFunctionDefinition<(), ()> for CustomDefinition {}
188/// ```
189#[allow(private_bounds)]
190pub trait IntoHostFunctionDefinition<C: HostSchema, Signature>:
191 adapter::Definition<C, Signature>
192{
193}
194
195impl<C: HostSchema, Signature, F> IntoHostFunctionDefinition<C, Signature> for F where
196 F: adapter::Definition<C, Signature>
197{
198}
199
200impl<C: HostSchema> adapter::Definition<C, ()> for HostFunction<C> {
201 fn into_definition(self, _token: Token) -> HostFunction<C> {
202 self
203 }
204}
205
206impl<C, F, A, R> adapter::Definition<C, (A, R)> for F
207where
208 C: HostSchema,
209 F: IntoHostFunction<A, R>,
210{
211 fn into_definition(self, _token: Token) -> HostFunction<C> {
212 HostFunction::pure(self)
213 }
214}
215
216impl<C: HostSchema> Rustia<C> {
217 /// Creates a live Rust function without installing a global binding.
218 ///
219 /// Script references keep the callback alive after its Rust handle is
220 /// dropped. Collection can release it once all references are gone. Decision
221 /// reset invalidates every handle and releases the VM's ownership of the
222 /// callback. Hardened leaves reject this constructor.
223 ///
224 /// Use [`register_function`](Self::register_function) for a global function
225 /// that should be restored after reset.
226 pub fn create_function<F, S>(&mut self, function: F) -> Result<Function>
227 where
228 F: IntoHostFunctionDefinition<C, S>,
229 {
230 self.create_named_function("<host>", function)
231 }
232
233 /// Creates a live Rust function with a name used in error reports.
234 /// The name does not install a binding or change callback ownership.
235 pub fn create_named_function<F, S>(
236 &mut self,
237 debug_name: impl Into<String>,
238 function: F,
239 ) -> Result<Function>
240 where
241 F: IntoHostFunctionDefinition<C, S>,
242 {
243 self.ensure_healthy()?;
244 if self.vm.settings().guest_surface.is_hardened_leaf() {
245 return Err(Error::from(
246 VmError::new(VmErrorKind::HardenedLeafViolation {
247 feature: "live function construction",
248 })
249 .without_source_location(),
250 ));
251 }
252 let function = function.into_definition(Token).into_op(debug_name.into());
253 let value = self
254 .vm
255 .create_retained_function(function)
256 .map_err(Error::from_engine)?;
257 Ok(Function::new(value, self.vm.decision_epoch()))
258 }
259
260 /// Installs a global Rust function and restores its binding after decision reset.
261 ///
262 /// Replacing the registration releases the old configuration's ownership.
263 /// Existing script references to the old function still work until reset.
264 /// Registration requires an idle VM without an active guest-state savepoint.
265 pub fn register_function<F, S>(&mut self, name: impl Into<String>, function: F) -> Result<()>
266 where
267 F: IntoHostFunctionDefinition<C, S>,
268 {
269 self.ensure_healthy()?;
270 let name = name.into();
271 if name.is_empty() {
272 return Err(Error::embed(
273 "host function name must not be empty".to_owned(),
274 ));
275 }
276 self.vm
277 .install_host_function(function.into_definition(Token).into_op(name))
278 .map_err(Error::from_engine)
279 }
280}