stak_engine/
engine.rs

1use crate::{EngineError, primitive_set::EnginePrimitiveSet};
2use any_fn::AnyFn;
3use stak_dynamic::SchemeValue;
4use stak_module::Module;
5use stak_vm::{Error, Value, Vm};
6
7/// A scripting engine.
8pub struct Engine<'a, 'b> {
9    vm: Vm<'a, EnginePrimitiveSet<'a, 'b>>,
10}
11
12impl<'a, 'b> Engine<'a, 'b> {
13    /// Creates a scripting engine.
14    pub fn new(
15        heap: &'a mut [Value],
16        functions: &'a mut [(&'a str, AnyFn<'b>)],
17    ) -> Result<Self, Error> {
18        Ok(Self {
19            vm: Vm::new(heap, EnginePrimitiveSet::new(functions))?,
20        })
21    }
22
23    /// Runs a module.
24    pub fn run<'c>(&mut self, module: &'c impl Module<'c>) -> Result<(), EngineError> {
25        self.vm.initialize(module.bytecode().iter().copied())?;
26        self.vm.run()
27    }
28
29    /// Registers a type compatible between Scheme and Rust.
30    ///
31    /// We register all types that this crate implements [`SchemeValue`] for to
32    /// the engines by default.
33    ///
34    /// For more information, see
35    /// [`DynamicPrimitiveSet`][stak_dynamic::DynamicPrimitiveSet].
36    pub fn register_type<T: SchemeValue + 'static>(&mut self) {
37        self.vm
38            .primitive_set_mut()
39            .dynamic_mut()
40            .register_type::<T>()
41    }
42}