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(heap: &'a mut [Value], functions: &'a mut [AnyFn<'b>]) -> Result<Self, Error> {
15        Ok(Self {
16            vm: Vm::new(heap, EnginePrimitiveSet::new(functions))?,
17        })
18    }
19
20    /// Runs a module.
21    pub fn run<'c>(&mut self, module: &'c impl Module<'c>) -> Result<(), EngineError> {
22        self.vm.initialize(module.bytecode().iter().copied())?;
23        self.vm.run()
24    }
25
26    /// Registers a type compatible between Scheme and Rust.
27    ///
28    /// We register all types that this crate implements [`SchemeValue`] for to
29    /// the engines by default.
30    ///
31    /// For more information, see
32    /// [`DynamicPrimitiveSet`][stak_dynamic::DynamicPrimitiveSet].
33    pub fn register_type<T: SchemeValue + 'static>(&mut self) {
34        self.vm
35            .primitive_set_mut()
36            .dynamic_mut()
37            .register_type::<T>()
38    }
39}