Skip to main content

rustia/
object_method.rs

1//! Synchronous method adapters. Receivers are checked before other arguments.
2
3use crate::function::{adapter::Token, host_arg_from_raw, host_embed_error, host_return_to_raw};
4use crate::{FromHostArgument, FromRustia, IntoHostReturn, Object, Result};
5use rustia_vm::{HostFunctionOp, OpCapability, Value, Vm};
6use std::any::{type_name, TypeId};
7use std::sync::Arc;
8
9pub(crate) mod adapter {
10    use super::*;
11
12    pub(crate) trait Read<T: 'static, A, R>: Send + Sync + 'static {
13        fn into_object_method(
14            self,
15            token: Token,
16            name: String,
17            fuel_cost: u32,
18            capability: OpCapability,
19        ) -> HostFunctionOp;
20    }
21
22    pub(crate) trait Write<T: 'static, A, R>: Send + Sync + 'static {
23        fn into_mut_object_method(
24            self,
25            token: Token,
26            name: String,
27            fuel_cost: u32,
28            capability: OpCapability,
29        ) -> HostFunctionOp;
30    }
31
32    pub(crate) trait Iterate<T: 'static, S, C, R>: Send + Sync + 'static {
33        fn into_object_iterator(
34            self,
35            token: Token,
36            fuel_cost: u32,
37            capability: OpCapability,
38        ) -> (HostFunctionOp, HostFunctionOp);
39    }
40
41    pub(crate) trait IterationReturn<C> {
42        type Item: IntoHostReturn;
43        fn into_iteration_return(self) -> Result<Option<Self::Item>>;
44        fn is_fallible() -> bool;
45    }
46
47    #[cfg(not(feature = "transferable"))]
48    pub(crate) trait IterationState: 'static {}
49    #[cfg(not(feature = "transferable"))]
50    impl<T: 'static> IterationState for T {}
51
52    #[cfg(feature = "transferable")]
53    pub(crate) trait IterationState: Send + Sync + 'static {}
54    #[cfg(feature = "transferable")]
55    impl<T: Send + Sync + 'static> IterationState for T {}
56}
57
58/// A read-only Rust-object method accepted by [`crate::ObjectType`].
59///
60/// Closures receive `&T`, then up to eight typed arguments. This sealed marker
61/// is implemented automatically; use ordinary closures or function pointers.
62#[allow(private_bounds)]
63pub trait IntoObjectMethod<T: 'static, A, R>: adapter::Read<T, A, R> {}
64impl<T: 'static, A, R, F: adapter::Read<T, A, R>> IntoObjectMethod<T, A, R> for F {}
65
66/// An immediately mutable Rust-object method accepted by [`crate::ObjectType`].
67///
68/// Closures receive `&mut T`, then up to eight typed arguments. Such methods
69/// declare external mutation and deterministic construction rejects them.
70#[allow(private_bounds)]
71pub trait IntoMutObjectMethod<T: 'static, A, R>: adapter::Write<T, A, R> {}
72impl<T: 'static, A, R, F: adapter::Write<T, A, R>> IntoMutObjectMethod<T, A, R> for F {}
73
74/// A typed generalized-iterator step accepted by [`crate::ObjectType`].
75///
76/// The factory receives the payload once and returns owned state for one loop.
77/// The step receives that private state and the previous control value. Returning
78/// `None` completes the loop. A returned tuple's
79/// first value is both Luau's next control value and the loop's first visible
80/// value, exactly like a regular Luau iterator function. Rustia requires that
81/// first value to have exactly the same type as the incoming control.
82///
83/// ```compile_fail
84/// use rustia::ObjectType;
85/// struct Values;
86/// let _ = ObjectType::<Values>::new("Values").iterator(1, |_| Ok::<_, rustia::Error>(()),
87///     |_: &mut (), _: Option<i64>| Some(("wrong control", 1_i64)));
88/// ```
89///
90/// An iterator step must return at least its next control value:
91///
92/// ```compile_fail
93/// use rustia::ObjectType;
94/// struct Values;
95/// let _ = ObjectType::<Values>::new("Values").iterator(1, |_| Ok::<_, rustia::Error>(()),
96///     |_: &mut (), _: Option<i64>| Some(()));
97/// ```
98#[allow(private_bounds)]
99pub trait IntoObjectIterator<T: 'static, S, C, R>: adapter::Iterate<T, S, C, R> {}
100impl<T: 'static, S, C, R, F: adapter::Iterate<T, S, C, R>> IntoObjectIterator<T, S, C, R> for F {}
101
102impl<C: IntoHostReturn> adapter::IterationReturn<C> for Option<C> {
103    type Item = C;
104
105    fn into_iteration_return(self) -> Result<Option<C>> {
106        Ok(self)
107    }
108
109    fn is_fallible() -> bool {
110        false
111    }
112}
113
114impl<C: IntoHostReturn> adapter::IterationReturn<C> for Result<Option<C>> {
115    type Item = C;
116
117    fn into_iteration_return(self) -> Result<Option<C>> {
118        self
119    }
120
121    fn is_fallible() -> bool {
122        true
123    }
124}
125
126macro_rules! iteration_tuple_return {
127    ($($name:ident),+ $(,)?) => {
128        impl<C, $($name),+> adapter::IterationReturn<C> for Option<(C, $($name,)+)>
129        where
130            (C, $($name,)+): IntoHostReturn,
131        {
132            type Item = (C, $($name,)+);
133
134            fn into_iteration_return(self) -> Result<Option<Self::Item>> {
135                Ok(self)
136            }
137
138            fn is_fallible() -> bool {
139                false
140            }
141        }
142
143        impl<C, $($name),+> adapter::IterationReturn<C> for Result<Option<(C, $($name,)+)>>
144        where
145            (C, $($name,)+): IntoHostReturn,
146        {
147            type Item = (C, $($name,)+);
148
149            fn into_iteration_return(self) -> Result<Option<Self::Item>> {
150                self
151            }
152
153            fn is_fallible() -> bool {
154                true
155            }
156        }
157    };
158}
159
160iteration_tuple_return!(A);
161iteration_tuple_return!(A, B);
162iteration_tuple_return!(A, B, D);
163iteration_tuple_return!(A, B, D, E);
164iteration_tuple_return!(A, B, D, E, G);
165iteration_tuple_return!(A, B, D, E, G, H);
166iteration_tuple_return!(A, B, D, E, G, H, I);
167
168pub(crate) fn checked_receiver<T: 'static>(
169    vm: &mut Vm,
170    args: &[Value],
171) -> rustia_vm::Result<rustia_vm::HostObjectOwner> {
172    vm.checked_host_object(
173        args.first().copied().unwrap_or_else(Value::nil),
174        TypeId::of::<T>(),
175        type_name::<T>(),
176    )
177}
178
179macro_rules! read_method {
180    ($count:expr; $($arg:ident),*) => {
181        impl<T, F, R, $($arg),*> adapter::Read<T, ($($arg,)*), R> for F
182        where T: 'static, F: Fn(&T, $($arg),*) -> R + Send + Sync + 'static,
183              R: IntoHostReturn, $($arg: FromHostArgument,)*
184        {
185            #[allow(non_snake_case, unused_mut, unused_variables)]
186            fn into_object_method(self, _: Token, name: String, fuel_cost: u32, capability: OpCapability) -> HostFunctionOp {
187                let diagnostic_name = name.clone();
188                HostFunctionOp::new(name, fuel_cost, capability, Arc::new(move |vm, args| {
189                    let object = checked_receiver::<T>(vm, args)?;
190                    let mut index = 1;
191                    $(let $arg = host_arg_from_raw(vm, args, index, &diagnostic_name)?; index += 1;)*
192                    let _ = index;
193                    let result = {
194                        let receiver = object.try_borrow::<T>()?;
195                        self(&receiver, $($arg),*)
196                    };
197                    host_return_to_raw(vm, &diagnostic_name, result)
198                })).with_signature(
199                    1 + $count,
200                    vec![type_name::<Object<T>>(), $(type_name::<$arg>()),*],
201                    R::rustia_type_names(Token), R::is_fallible(Token),
202                )
203            }
204        }
205    };
206}
207
208macro_rules! write_method {
209    ($count:expr; $($arg:ident),*) => {
210        impl<T, F, R, $($arg),*> adapter::Write<T, ($($arg,)*), R> for F
211        where T: 'static, F: Fn(&mut T, $($arg),*) -> R + Send + Sync + 'static,
212              R: IntoHostReturn, $($arg: FromHostArgument,)*
213        {
214            #[allow(non_snake_case, unused_mut, unused_variables)]
215            fn into_mut_object_method(self, _: Token, name: String, fuel_cost: u32, capability: OpCapability) -> HostFunctionOp {
216                let diagnostic_name = name.clone();
217                HostFunctionOp::new(name, fuel_cost, capability, Arc::new(move |vm, args| {
218                    let object = checked_receiver::<T>(vm, args)?;
219                    let mut index = 1;
220                    $(let $arg = host_arg_from_raw(vm, args, index, &diagnostic_name)?; index += 1;)*
221                    let _ = index;
222                    let result = {
223                        let mut receiver = object.try_borrow_mut::<T>()?;
224                        self(&mut receiver, $($arg),*)
225                    };
226                    host_return_to_raw(vm, &diagnostic_name, result)
227                })).with_signature(
228                    1 + $count,
229                    vec![type_name::<Object<T>>(), $(type_name::<$arg>()),*],
230                    R::rustia_type_names(Token), R::is_fallible(Token),
231                )
232            }
233        }
234    };
235}
236
237read_method!(0;);
238read_method!(1; A);
239read_method!(2; A, B);
240read_method!(3; A, B, C);
241read_method!(4; A, B, C, D);
242read_method!(5; A, B, C, D, E);
243read_method!(6; A, B, C, D, E, G);
244read_method!(7; A, B, C, D, E, G, H);
245read_method!(8; A, B, C, D, E, G, H, I);
246write_method!(0;);
247write_method!(1; A);
248write_method!(2; A, B);
249write_method!(3; A, B, C);
250write_method!(4; A, B, C, D);
251write_method!(5; A, B, C, D, E);
252write_method!(6; A, B, C, D, E, G);
253write_method!(7; A, B, C, D, E, G, H);
254write_method!(8; A, B, C, D, E, G, H, I);
255
256impl<T, Factory, Step, S, C, R> adapter::Iterate<T, S, C, R> for (Factory, Step)
257where
258    T: 'static,
259    Factory: Fn(&T) -> Result<S> + Send + Sync + 'static,
260    Step: Fn(&mut S, Option<C>) -> R + Send + Sync + 'static,
261    S: adapter::IterationState,
262    C: FromRustia,
263    R: adapter::IterationReturn<C>,
264{
265    fn into_object_iterator(
266        self,
267        _: Token,
268        fuel_cost: u32,
269        capability: OpCapability,
270    ) -> (HostFunctionOp, HostFunctionOp) {
271        let (factory, step) = self;
272        let factory_op = HostFunctionOp::new(
273            "__iter",
274            fuel_cost,
275            capability,
276            Arc::new(move |vm, args| {
277                let receiver_raw = args.first().copied().unwrap_or_else(Value::nil);
278                let object = checked_receiver::<T>(vm, args)?;
279                let state = {
280                    let receiver = object.try_borrow::<T>()?;
281                    factory(&receiver)
282                }
283                .map_err(|error| host_embed_error("__iter", "return value", error))?;
284                let iterator = vm.host_object_iterator_step(receiver_raw)?;
285                let state = vm.create_host_iterator_state(
286                    receiver_raw,
287                    TypeId::of::<S>(),
288                    type_name::<S>(),
289                    Box::new(state),
290                )?;
291                Ok(vec![iterator, state, Value::nil()])
292            }),
293        )
294        .with_signature(
295            1,
296            vec![type_name::<Object<T>>()],
297            vec!["iterator", type_name::<S>(), "nil"],
298            true,
299        );
300        let step_op = HostFunctionOp::new(
301            "__iter_step",
302            fuel_cost,
303            capability,
304            Arc::new(move |vm, args| {
305                let control = host_arg_from_raw::<Option<C>>(vm, args, 1, "__iter")?;
306                let state = checked_receiver::<S>(vm, args)?;
307                let result = {
308                    let mut state = state.try_borrow_mut::<S>()?;
309                    step(&mut state, control)
310                };
311                match result
312                    .into_iteration_return()
313                    .map_err(|error| host_embed_error("__iter", "return value", error))?
314                {
315                    Some(values) => host_return_to_raw(vm, "__iter", values),
316                    None => Ok(vec![Value::nil()]),
317                }
318            }),
319        )
320        .with_signature(
321            2,
322            vec![type_name::<S>(), type_name::<Option<C>>()],
323            <R::Item as crate::function::adapter::Return>::rustia_type_names(Token),
324            R::is_fallible(),
325        );
326        (factory_op, step_op)
327    }
328}