micro_games_kit/
scripting.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
use intuicio_backend_vm::scope::VmScope;
use intuicio_core::{context::Context, host::Host, registry::Registry};
use intuicio_frontend_simpleton::{
    library,
    script::{SimpletonModule, SimpletonPackage, SimpletonScriptExpression},
    Reference, Type,
};
use serde::{Deserialize, Serialize};

#[macro_export]
macro_rules! script_contents {
    ( $const_name:ident => $($path:literal),* ) => {
        const $const_name: &[&str] = &[ $( include_str!($path) ),* ];
    };
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ScriptingConfig {
    pub stack_capacity: usize,
    pub registers_capacity: usize,
}

impl Default for ScriptingConfig {
    fn default() -> Self {
        Self {
            stack_capacity: 10240,
            registers_capacity: 10240,
        }
    }
}

pub fn create_host(
    config: ScriptingConfig,
    script_contents: &[&str],
    registry_setup: impl IntoIterator<Item = fn(&mut Registry)>,
) {
    let package = SimpletonPackage {
        modules: script_contents
            .iter()
            .enumerate()
            .map(|(index, content)| (index.to_string(), SimpletonModule::parse(content).unwrap()))
            .collect(),
    };
    let mut registry = Registry::default();
    library::install(&mut registry);
    for setup in registry_setup.into_iter() {
        (setup)(&mut registry);
    }
    package
        .compile()
        .install::<VmScope<SimpletonScriptExpression>>(&mut registry, None);
    let context = Context::new(config.stack_capacity, config.registers_capacity);
    let host = Host::new(context, registry.into());
    if host.push_global().is_err() {
        panic!("Could not make global scripting host!");
    }
}

pub fn destroy_host() {
    Host::pop_global();
}

pub fn call_function(name: &str, module_name: &str, args: &[Reference]) -> Reference {
    Host::with_global(|host| {
        let Some(handle) = host.find_function(name, module_name, None) else {
            return Reference::null();
        };
        let (context, registry) = host.context_and_registry();
        for arg in args.iter().rev() {
            context.stack().push(arg.clone());
        }
        handle.invoke(context, registry);
        context.stack().pop().unwrap_or_default()
    })
    .unwrap_or_default()
}

pub fn call_object(object: Reference, name: &str, args: &[Reference]) -> Reference {
    Host::with_global(move |host| {
        let Some(ty) = object.type_of() else {
            return Reference::null();
        };
        let Some(ty) = ty.handle() else {
            return Reference::null();
        };
        let Some(handle) = host.find_function(name, ty.module_name().unwrap_or_default(), None)
        else {
            return Reference::null();
        };
        let (context, registry) = host.context_and_registry();
        for arg in args.iter().rev() {
            context.stack().push(arg.clone());
        }
        context.stack().push(object);
        handle.invoke(context, registry);
        context.stack().pop().unwrap_or_default()
    })
    .unwrap_or_default()
}

pub fn new(type_name: &str, module_name: &str) -> Reference {
    new_init(type_name, module_name, &[])
}

pub fn new_init(type_name: &str, module_name: &str, properties: &[(&str, Reference)]) -> Reference {
    Host::with_global(move |host| {
        let ty = Reference::new_type(
            Type::by_name(type_name, module_name, host.registry()).unwrap(),
            host.registry(),
        );
        let properties = Reference::new_map(
            properties
                .iter()
                .map(|(name, value)| ((*name).to_owned(), value.clone()))
                .collect(),
            host.registry(),
        );
        library::reflect::new(ty, properties)
    })
    .unwrap_or_default()
}

pub fn new_typed<T: 'static>(value: T) -> Reference {
    Host::with_global(move |host| Reference::new(value, host.registry())).unwrap_or_default()
}

pub fn get(object: Reference, field: &str) -> Reference {
    object
        .read_object()
        .unwrap()
        .read_field::<Reference>(field)
        .unwrap()
        .clone()
}

pub fn set(mut object: Reference, field: &str, value: Reference) {
    *object
        .write_object()
        .unwrap()
        .write_field::<Reference>(field)
        .unwrap() = value;
}