Skip to main content

rustia/
object_context.rs

1//! Object methods use the same borrowed views, dispatcher, and journal as functions.
2
3use crate::function::{adapter::Token, host_arg_from_raw, host_return_to_raw};
4use crate::invocation::{
5    ContextHostFunction, EffectView, ExternalView, InputView, MakeCapabilityView, SlotReadView,
6    SlotWriteView,
7};
8use crate::object_method::checked_receiver;
9use crate::{FromHostArgument, HostSchema, IntoHostReturn, Object, ObjectType};
10use rustia_vm::OpCapability;
11use std::any::type_name;
12
13mod adapter {
14    use super::*;
15
16    pub(crate) trait Read<T: 'static, H: HostSchema, A, R, V>:
17        Send + Sync + 'static
18    {
19        fn into_context_object_method(
20            self,
21            token: Token,
22            name: String,
23            fuel_cost: u32,
24            capability: OpCapability,
25        ) -> ContextHostFunction<H>;
26    }
27
28    pub(crate) trait Write<T: 'static, H: HostSchema, A, R, V>:
29        Send + Sync + 'static
30    {
31        fn into_mut_context_object_method(
32            self,
33            token: Token,
34            name: String,
35            fuel_cost: u32,
36            capability: OpCapability,
37        ) -> ContextHostFunction<H>;
38    }
39}
40
41/// A read-only object method that borrows the current invocation's input.
42///
43/// Closures receive `&T`, [`crate::Input`], then up to eight typed arguments.
44/// This sealed marker is implemented automatically for matching closures and
45/// function pointers.
46///
47/// ```compile_fail
48/// struct CustomMethod;
49/// impl rustia::IntoInputObjectMethod<(), (), (), ()> for CustomMethod {}
50/// ```
51#[allow(private_bounds)]
52pub trait IntoInputObjectMethod<T: 'static, H: HostSchema, A, R>:
53    adapter::Read<T, H, A, R, InputView>
54{
55}
56impl<T: 'static, H: HostSchema, A, R, F> IntoInputObjectMethod<T, H, A, R> for F where
57    F: adapter::Read<T, H, A, R, InputView>
58{
59}
60
61/// A read-only object method that borrows the invocation's saved slot snapshot.
62///
63/// Closures receive `&T`, [`crate::Slots`], then up to eight typed arguments.
64/// This sealed marker is implemented automatically for matching callbacks.
65#[allow(private_bounds)]
66pub trait IntoSlotReadObjectMethod<T: 'static, H: HostSchema, A, R>:
67    adapter::Read<T, H, A, R, SlotReadView>
68{
69}
70impl<T: 'static, H: HostSchema, A, R, F> IntoSlotReadObjectMethod<T, H, A, R> for F where
71    F: adapter::Read<T, H, A, R, SlotReadView>
72{
73}
74
75/// An object method that stages effects in the invocation's existing journal.
76///
77/// Closures receive `&T`, [`crate::Effects`], then up to eight typed arguments.
78/// This sealed marker is implemented automatically for matching callbacks.
79#[allow(private_bounds)]
80pub trait IntoEffectObjectMethod<T: 'static, H: HostSchema, A, R>:
81    adapter::Read<T, H, A, R, EffectView>
82{
83}
84impl<T: 'static, H: HostSchema, A, R, F> IntoEffectObjectMethod<T, H, A, R> for F where
85    F: adapter::Read<T, H, A, R, EffectView>
86{
87}
88
89/// An object method that stages slot writes in the invocation's existing journal.
90///
91/// Closures receive `&T`, [`crate::SlotWrites`], then up to eight typed arguments.
92/// This sealed marker is implemented automatically for matching callbacks.
93#[allow(private_bounds)]
94pub trait IntoSlotWriteObjectMethod<T: 'static, H: HostSchema, A, R>:
95    adapter::Read<T, H, A, R, SlotWriteView>
96{
97}
98impl<T: 'static, H: HostSchema, A, R, F> IntoSlotWriteObjectMethod<T, H, A, R> for F where
99    F: adapter::Read<T, H, A, R, SlotWriteView>
100{
101}
102
103/// An object method with immediate access to external application state.
104///
105/// Closures receive `&T`, [`crate::HostMut`], then up to eight typed arguments.
106/// This sealed marker is implemented automatically for matching callbacks.
107#[allow(private_bounds)]
108pub trait IntoExternalObjectMethod<T: 'static, H: HostSchema, A, R>:
109    adapter::Read<T, H, A, R, ExternalView>
110{
111}
112impl<T: 'static, H: HostSchema, A, R, F> IntoExternalObjectMethod<T, H, A, R> for F where
113    F: adapter::Read<T, H, A, R, ExternalView>
114{
115}
116
117/// A method that may change its payload and external application state immediately.
118///
119/// Closures receive `&mut T`, [`crate::HostMut`], then up to eight typed arguments.
120/// This sealed marker is implemented automatically for matching callbacks.
121#[allow(private_bounds)]
122pub trait IntoExternalMutObjectMethod<T: 'static, H: HostSchema, A, R>:
123    adapter::Write<T, H, A, R, ExternalView>
124{
125}
126impl<T: 'static, H: HostSchema, A, R, F> IntoExternalMutObjectMethod<T, H, A, R> for F where
127    F: adapter::Write<T, H, A, R, ExternalView>
128{
129}
130
131impl<T: 'static, H: HostSchema> ObjectType<T, H> {
132    /// Adds a read-only method over this invocation's deterministic input.
133    pub fn input<F, A, R>(mut self, name: impl Into<String>, fuel_cost: u32, method: F) -> Self
134    where
135        F: IntoInputObjectMethod<T, H, A, R>,
136    {
137        self.methods.push(
138            method
139                .into_context_object_method(
140                    Token,
141                    name.into(),
142                    fuel_cost,
143                    OpCapability::ReadsDeterministicInput,
144                )
145                .into_op(),
146        );
147        self
148    }
149
150    /// Adds a read-only method over this invocation's saved slot snapshot.
151    pub fn slot_read<F, A, R>(mut self, name: impl Into<String>, fuel_cost: u32, method: F) -> Self
152    where
153        F: IntoSlotReadObjectMethod<T, H, A, R>,
154    {
155        self.methods.push(
156            method
157                .into_context_object_method(
158                    Token,
159                    name.into(),
160                    fuel_cost,
161                    OpCapability::ReadsSlotState,
162                )
163                .into_op(),
164        );
165        self
166    }
167
168    /// Adds a method that stages effects with `&T` and [`crate::Effects`].
169    ///
170    /// Effects share the invocation's ordering and output limits. A failing
171    /// method discards its own staged suffix; a failure escaping the outer
172    /// invocation discards all its records.
173    pub fn effect<F, A, R>(mut self, name: impl Into<String>, fuel_cost: u32, method: F) -> Self
174    where
175        F: IntoEffectObjectMethod<T, H, A, R>,
176    {
177        self.methods.push(
178            method
179                .into_context_object_method(
180                    Token,
181                    name.into(),
182                    fuel_cost,
183                    OpCapability::EmitsDeterministicEffect,
184                )
185                .into_op(),
186        );
187        self
188    }
189
190    /// Adds a method that stages saved-state changes with [`crate::SlotWrites`].
191    ///
192    /// Slot writes use the same journal, ordering, and limits as effects.
193    pub fn slot_write<F, A, R>(mut self, name: impl Into<String>, fuel_cost: u32, method: F) -> Self
194    where
195        F: IntoSlotWriteObjectMethod<T, H, A, R>,
196    {
197        self.methods.push(
198            method
199                .into_context_object_method(
200                    Token,
201                    name.into(),
202                    fuel_cost,
203                    OpCapability::WritesSlotEffect,
204                )
205                .into_op(),
206        );
207        self
208    }
209
210    /// Adds a read-only payload method with immediate external-state access.
211    ///
212    /// The callback receives `&T`, then [`crate::HostMut`]. This declares
213    /// external mutable state and is rejected by deterministic construction.
214    /// Application changes are outside invocation and installation rollback.
215    pub fn external<F, A, R>(mut self, name: impl Into<String>, fuel_cost: u32, method: F) -> Self
216    where
217        F: IntoExternalObjectMethod<T, H, A, R>,
218    {
219        self.methods.push(
220            method
221                .into_context_object_method(
222                    Token,
223                    name.into(),
224                    fuel_cost,
225                    OpCapability::ReadsExternalMutableState,
226                )
227                .into_op(),
228        );
229        self
230    }
231
232    /// Adds a read-only payload method that performs nondeterministic external work.
233    ///
234    /// The callback receives `&T`, then [`crate::HostMut`]. Deterministic
235    /// construction rejects the definition. External effects are immediate.
236    pub fn nondeterministic<F, A, R>(
237        mut self,
238        name: impl Into<String>,
239        fuel_cost: u32,
240        method: F,
241    ) -> Self
242    where
243        F: IntoExternalObjectMethod<T, H, A, R>,
244    {
245        self.methods.push(
246            method
247                .into_context_object_method(
248                    Token,
249                    name.into(),
250                    fuel_cost,
251                    OpCapability::NondeterministicEffect,
252                )
253                .into_op(),
254        );
255        self
256    }
257
258    /// Adds a method with `&mut T` and immediate external-state access.
259    ///
260    /// This declares external mutable state. Payload and application changes
261    /// survive later script errors and failed installations. Reset drops the
262    /// payload; it does not undo changes to the external application.
263    pub fn external_mut<F, A, R>(
264        mut self,
265        name: impl Into<String>,
266        fuel_cost: u32,
267        method: F,
268    ) -> Self
269    where
270        F: IntoExternalMutObjectMethod<T, H, A, R>,
271    {
272        self.methods.push(
273            method
274                .into_mut_context_object_method(
275                    Token,
276                    name.into(),
277                    fuel_cost,
278                    OpCapability::ReadsExternalMutableState,
279                )
280                .into_op(),
281        );
282        self
283    }
284
285    /// Adds a mutable payload method that performs nondeterministic external work.
286    ///
287    /// Receives `&mut T`, then [`crate::HostMut`]. Both changes are immediate,
288    /// and deterministic construction rejects the complete definition.
289    pub fn nondeterministic_mut<F, A, R>(
290        mut self,
291        name: impl Into<String>,
292        fuel_cost: u32,
293        method: F,
294    ) -> Self
295    where
296        F: IntoExternalMutObjectMethod<T, H, A, R>,
297    {
298        self.methods.push(
299            method
300                .into_mut_context_object_method(
301                    Token,
302                    name.into(),
303                    fuel_cost,
304                    OpCapability::NondeterministicEffect,
305                )
306                .into_op(),
307        );
308        self
309    }
310}
311
312macro_rules! read_method {
313    ($count:expr; $($arg:ident),*) => {
314        impl<T, H, F, R, V, $($arg),*> adapter::Read<T, H, ($($arg,)*), R, V> for F
315        where
316            T: 'static, H: HostSchema, V: MakeCapabilityView<H> + 'static,
317            F: for<'call> Fn(&T, V::View<'call>, $($arg),*) -> R + Send + Sync + 'static,
318            R: IntoHostReturn, $($arg: FromHostArgument,)*
319        {
320            #[allow(non_snake_case, unused_mut, unused_variables)]
321            fn into_context_object_method(self, _: Token, name: String, fuel_cost: u32, capability: OpCapability) -> ContextHostFunction<H> {
322                let diagnostic_name = name.clone();
323                ContextHostFunction {
324                    name, fuel_cost, capability,
325                    parameter_count: 1 + $count,
326                    parameter_types: vec![type_name::<Object<T>>(), $(type_name::<$arg>()),*],
327                    return_types: R::rustia_type_names(Token),
328                    fallible: R::is_fallible(Token),
329                    handler: Box::new(move |vm, context, journal, args| {
330                        let object = checked_receiver::<T>(vm, args)?;
331                        let mut index = 1;
332                        $(let $arg = host_arg_from_raw(vm, args, index, &diagnostic_name)?; index += 1;)*
333                        let _ = index;
334                        let result = {
335                            let receiver = object.try_borrow::<T>()?;
336                            let view = V::make(context, journal);
337                            self(&receiver, view, $($arg),*)
338                        };
339                        host_return_to_raw(vm, &diagnostic_name, result)
340                    }),
341                }
342            }
343        }
344    };
345}
346
347macro_rules! write_method {
348    ($count:expr; $($arg:ident),*) => {
349        impl<T, H, F, R, V, $($arg),*> adapter::Write<T, H, ($($arg,)*), R, V> for F
350        where
351            T: 'static, H: HostSchema, V: MakeCapabilityView<H> + 'static,
352            F: for<'call> Fn(&mut T, V::View<'call>, $($arg),*) -> R + Send + Sync + 'static,
353            R: IntoHostReturn, $($arg: FromHostArgument,)*
354        {
355            #[allow(non_snake_case, unused_mut, unused_variables)]
356            fn into_mut_context_object_method(self, _: Token, name: String, fuel_cost: u32, capability: OpCapability) -> ContextHostFunction<H> {
357                let diagnostic_name = name.clone();
358                ContextHostFunction {
359                    name, fuel_cost, capability,
360                    parameter_count: 1 + $count,
361                    parameter_types: vec![type_name::<Object<T>>(), $(type_name::<$arg>()),*],
362                    return_types: R::rustia_type_names(Token),
363                    fallible: R::is_fallible(Token),
364                    handler: Box::new(move |vm, context, journal, args| {
365                        let object = checked_receiver::<T>(vm, args)?;
366                        let mut index = 1;
367                        $(let $arg = host_arg_from_raw(vm, args, index, &diagnostic_name)?; index += 1;)*
368                        let _ = index;
369                        let result = {
370                            let mut receiver = object.try_borrow_mut::<T>()?;
371                            let view = V::make(context, journal);
372                            self(&mut receiver, view, $($arg),*)
373                        };
374                        host_return_to_raw(vm, &diagnostic_name, result)
375                    }),
376                }
377            }
378        }
379    };
380}
381
382read_method!(0;);
383read_method!(1; A);
384read_method!(2; A, B);
385read_method!(3; A, B, C);
386read_method!(4; A, B, C, D);
387read_method!(5; A, B, C, D, E);
388read_method!(6; A, B, C, D, E, G);
389read_method!(7; A, B, C, D, E, G, I);
390read_method!(8; A, B, C, D, E, G, I, J);
391write_method!(0;);
392write_method!(1; A);
393write_method!(2; A, B);
394write_method!(3; A, B, C);
395write_method!(4; A, B, C, D);
396write_method!(5; A, B, C, D, E);
397write_method!(6; A, B, C, D, E, G);
398write_method!(7; A, B, C, D, E, G, I);
399write_method!(8; A, B, C, D, E, G, I, J);
400
401#[cfg(test)]
402mod tests {
403    use super::*;
404    use crate::{
405        Effects, HostContext, HostMut, Input, InvocationLimits, RustiaBuilder, SlotWrites, Slots,
406    };
407
408    struct Schema;
409    impl HostSchema for Schema {
410        type Input = i64;
411        type Slots = i64;
412        type External = i64;
413        type Effect = i64;
414        type SlotWrite = i64;
415        type Record = (u32, &'static str, i64);
416    }
417
418    struct Context<'a> {
419        input: &'a i64,
420        slots: &'a i64,
421        external: &'a mut i64,
422    }
423
424    impl HostContext<Schema> for Context<'_> {
425        fn input(&self) -> &i64 {
426            self.input
427        }
428        fn slots(&self) -> &i64 {
429            self.slots
430        }
431        fn external_mut(&mut self) -> &mut i64 {
432            self.external
433        }
434        fn record_effect(&self, sequence: u32, effect: i64) -> (u32, &'static str, i64) {
435            (sequence, "effect", effect)
436        }
437        fn record_slot_write(&self, sequence: u32, write: i64) -> (u32, &'static str, i64) {
438            (sequence, "slot", write)
439        }
440        fn record_bytes(&self, _: &(u32, &'static str, i64)) -> u64 {
441            16
442        }
443    }
444
445    struct Actor(i64);
446
447    fn input_function(actor: &Actor, input: Input<'_, Schema>) -> i64 {
448        actor.0 + input.get()
449    }
450
451    fn add_input<F, A, R>(
452        definition: ObjectType<Actor, Schema>,
453        method: F,
454    ) -> ObjectType<Actor, Schema>
455    where
456        F: IntoInputObjectMethod<Actor, Schema, A, R>,
457    {
458        definition.input("input", 1, method)
459    }
460
461    #[test]
462    fn views_use_each_calls_borrowed_context_and_the_existing_ordered_journal() {
463        let definition = add_input(ObjectType::<Actor, Schema>::new("Actor"), input_function)
464            .slot_read("slot", 1, |actor: &Actor, slots: Slots<'_, Schema>| {
465                actor.0 + slots.get()
466            })
467            .effect(
468                "emit",
469                1,
470                |actor: &Actor, mut effects: Effects<'_, Schema>, amount: i64| {
471                    effects.emit(actor.0 + amount)
472                },
473            )
474            .slot_write(
475                "write",
476                1,
477                |actor: &Actor, mut writes: SlotWrites<'_, Schema>, amount: i64| {
478                    writes.write(actor.0 + amount)
479                },
480            )
481            .external(
482                "external",
483                1,
484                |actor: &Actor, mut host: HostMut<'_, Schema>| actor.0 + *host.get_mut(),
485            )
486            .nondeterministic(
487                "external_add",
488                1,
489                |actor: &Actor, mut host: HostMut<'_, Schema>, amount: i64| {
490                    *host.get_mut() += actor.0 + amount;
491                },
492            )
493            .external_mut(
494                "set",
495                1,
496                |actor: &mut Actor, mut host: HostMut<'_, Schema>, amount: i64| {
497                    actor.0 = amount;
498                    *host.get_mut() += amount;
499                },
500            )
501            .nondeterministic_mut(
502                "add",
503                1,
504                |actor: &mut Actor, mut host: HostMut<'_, Schema>, amount: i64| {
505                    actor.0 += amount;
506                    *host.get_mut() += amount;
507                },
508            );
509        let mut lua = RustiaBuilder::standard()
510            .without_stdout()
511            .build_for_host::<Schema>()
512            .unwrap();
513        lua.register_object_type(definition).unwrap();
514        let actor = lua.create_object(Actor(2)).unwrap();
515        lua.globals()
516            .unwrap()
517            .set_live(&mut lua, "actor", &actor.as_value())
518            .unwrap();
519        let mut external = 10;
520        for input in [3, 7] {
521            let slots = 5;
522            let mut context = Context {
523                input: &input,
524                slots: &slots,
525                external: &mut external,
526            };
527            let outcome = lua.invoke(&mut context, InvocationLimits::new(10_000).with_max_records(2).with_max_record_bytes(64), |call| {
528                call.load("actor:emit(8); actor:write(9); return {actor:input(), actor:slot(), actor:external()}")
529                    .eval::<Vec<i64>>()
530            }).unwrap();
531            assert_eq!(outcome.value, vec![input + 2, 7, 12]);
532            assert_eq!(outcome.records, [(0, "effect", 10), (1, "slot", 11)]);
533        }
534        let mut context = Context {
535            input: &0,
536            slots: &0,
537            external: &mut external,
538        };
539        lua.invoke(
540            &mut context,
541            InvocationLimits::new(10_000)
542                .with_max_records(2)
543                .with_max_record_bytes(64),
544            |call| {
545                call.load("actor:external_add(1); actor:set(4); actor:add(3); error('later')")
546                    .exec()
547            },
548        )
549        .unwrap_err();
550        assert_eq!(external, 20);
551        let mut context = Context {
552            input: &0,
553            slots: &0,
554            external: &mut external,
555        };
556        let outcome = lua
557            .invoke(
558                &mut context,
559                InvocationLimits::new(10_000)
560                    .with_max_records(2)
561                    .with_max_record_bytes(64),
562                |call| call.load("return actor:input()").eval::<i64>(),
563            )
564            .unwrap();
565        assert_eq!(outcome.value, 7);
566        assert!(outcome.records.is_empty());
567    }
568
569    #[test]
570    fn contextual_adapters_support_eight_explicit_arguments() {
571        let definition = ObjectType::<Actor, Schema>::new("Actor")
572            .input(
573                "sum",
574                1,
575                |actor: &Actor,
576                 input: Input<'_, Schema>,
577                 a: i64,
578                 b: i64,
579                 c: i64,
580                 d: i64,
581                 e: i64,
582                 f: i64,
583                 g: i64,
584                 h: i64| { actor.0 + input.get() + a + b + c + d + e + f + g + h },
585            )
586            .external_mut(
587                "sum_mut",
588                1,
589                |actor: &mut Actor,
590                 mut host: HostMut<'_, Schema>,
591                 a: i64,
592                 b: i64,
593                 c: i64,
594                 d: i64,
595                 e: i64,
596                 f: i64,
597                 g: i64,
598                 h: i64| {
599                    actor.0 += a + b + c + d + e + f + g + h;
600                    *host.get_mut() += actor.0;
601                    actor.0
602                },
603            );
604        let mut lua = RustiaBuilder::standard()
605            .without_stdout()
606            .build_for_host::<Schema>()
607            .unwrap();
608        lua.register_object_type(definition).unwrap();
609        let actor = lua.create_object(Actor(2)).unwrap();
610        lua.globals()
611            .unwrap()
612            .set_live(&mut lua, "actor", &actor.as_value())
613            .unwrap();
614        let mut external = 0;
615        let mut context = Context {
616            input: &3,
617            slots: &0,
618            external: &mut external,
619        };
620        let outcome = lua
621            .invoke(
622                &mut context,
623                InvocationLimits::new(10_000)
624                    .with_max_records(2)
625                    .with_max_record_bytes(64),
626                |call| {
627                    call.load("return {actor:sum(1,2,3,4,5,6,7,8), actor:sum_mut(1,2,3,4,5,6,7,8)}")
628                        .eval::<Vec<i64>>()
629                },
630            )
631            .unwrap();
632        assert_eq!(outcome.value, vec![41, 38]);
633        assert_eq!(external, 38);
634    }
635
636    #[test]
637    fn wrong_receivers_do_not_project_the_host_context() {
638        struct Observe {
639            input_reads: std::cell::Cell<u32>,
640            external_reads: u32,
641            value: i64,
642        }
643        impl HostContext<Schema> for Observe {
644            fn input(&self) -> &i64 {
645                self.input_reads.set(self.input_reads.get() + 1);
646                &self.value
647            }
648            fn slots(&self) -> &i64 {
649                &self.value
650            }
651            fn external_mut(&mut self) -> &mut i64 {
652                self.external_reads += 1;
653                &mut self.value
654            }
655            fn record_effect(&self, sequence: u32, effect: i64) -> (u32, &'static str, i64) {
656                (sequence, "effect", effect)
657            }
658            fn record_slot_write(&self, sequence: u32, write: i64) -> (u32, &'static str, i64) {
659                (sequence, "slot", write)
660            }
661            fn record_bytes(&self, _: &(u32, &'static str, i64)) -> u64 {
662                16
663            }
664        }
665        let mut lua = RustiaBuilder::standard()
666            .without_stdout()
667            .build_for_host::<Schema>()
668            .unwrap();
669        lua.register_object_type(
670            ObjectType::<Actor, Schema>::new("Actor")
671                .input("read", 1, |_: &Actor, input: Input<'_, Schema>| {
672                    *input.get()
673                })
674                .external_mut(
675                    "change",
676                    1,
677                    |_: &mut Actor, mut host: HostMut<'_, Schema>| *host.get_mut() += 1,
678                ),
679        )
680        .unwrap();
681        let actor = lua.create_object(Actor(2)).unwrap();
682        lua.globals()
683            .unwrap()
684            .set_live(&mut lua, "actor", &actor.as_value())
685            .unwrap();
686        let mut context = Observe {
687            input_reads: std::cell::Cell::new(0),
688            external_reads: 0,
689            value: 9,
690        };
691        let outcome = lua.invoke(&mut context, InvocationLimits::new(10_000), |call| {
692            call.load("assert(not pcall(actor.read, {})); assert(not pcall(actor.change, {})); return actor:read()")
693                .eval::<i64>()
694        }).unwrap();
695        assert_eq!(outcome.value, 9);
696        assert_eq!(context.input_reads.get(), 1);
697        assert_eq!(context.external_reads, 0);
698    }
699}