intuicio_frontend_simpleton/library/
closure.rs

1use crate::{Array, Function, Reference};
2use intuicio_core::{context::Context, registry::Registry, IntuicioStruct};
3use intuicio_derive::{intuicio_method, intuicio_methods, IntuicioStruct};
4
5#[derive(IntuicioStruct, Default)]
6#[intuicio(name = "Closure", module_name = "closure", override_send = false)]
7pub struct Closure {
8    #[intuicio(ignore)]
9    pub function: Function,
10    #[intuicio(ignore)]
11    pub captured: Array,
12}
13
14#[intuicio_methods(module_name = "closure")]
15impl Closure {
16    #[allow(clippy::new_ret_no_self)]
17    #[intuicio_method(use_registry)]
18    pub fn new(registry: &Registry, function: Reference, captured: Reference) -> Reference {
19        Reference::new(
20            Closure {
21                function: function.read::<Function>().unwrap().clone(),
22                captured: captured.read::<Array>().unwrap().clone(),
23            },
24            registry,
25        )
26    }
27
28    pub fn invoke(
29        &self,
30        context: &mut Context,
31        registry: &Registry,
32        arguments: &[Reference],
33    ) -> Reference {
34        for argument in arguments.iter().rev() {
35            context.stack().push(argument.clone());
36        }
37        for argument in self.captured.iter().rev() {
38            context.stack().push(argument.clone());
39        }
40        self.function.handle().unwrap().invoke(context, registry);
41        context.stack().pop::<Reference>().unwrap_or_default()
42    }
43
44    #[intuicio_method(use_context, use_registry)]
45    pub fn call(
46        context: &mut Context,
47        registry: &Registry,
48        closure: Reference,
49        arguments: Reference,
50    ) -> Reference {
51        closure.read::<Closure>().unwrap().invoke(
52            context,
53            registry,
54            arguments.read::<Array>().as_ref().unwrap(),
55        )
56    }
57}
58
59pub fn install(registry: &mut Registry) {
60    registry.add_type(Closure::define_struct(registry));
61    registry.add_function(Closure::new__define_function(registry));
62    registry.add_function(Closure::call__define_function(registry));
63}