rune/runtime/
runtime_context.rs

1use core::fmt;
2
3use crate as rune;
4use crate::alloc::prelude::*;
5use crate::hash;
6use crate::runtime::{ConstConstructImpl, ConstValue};
7use crate::Hash;
8
9use super::FunctionHandler;
10
11/// Static run context visible to the virtual machine.
12///
13/// This contains:
14/// * Declared functions.
15/// * Declared instance functions.
16/// * Built-in type checks.
17#[derive(Default, TryClone)]
18pub struct RuntimeContext {
19    /// Registered native function handlers.
20    functions: hash::Map<FunctionHandler>,
21    /// Named constant values
22    constants: hash::Map<ConstValue>,
23    /// Constant constructors.
24    construct: hash::Map<ConstConstructImpl>,
25}
26
27assert_impl!(RuntimeContext: Send + Sync);
28
29impl RuntimeContext {
30    pub(crate) fn new(
31        functions: hash::Map<FunctionHandler>,
32        constants: hash::Map<ConstValue>,
33        construct: hash::Map<ConstConstructImpl>,
34    ) -> Self {
35        Self {
36            functions,
37            constants,
38            construct,
39        }
40    }
41
42    /// Lookup the given native function handler in the context.
43    #[inline]
44    pub fn function(&self, hash: &Hash) -> Option<&FunctionHandler> {
45        self.functions.get(hash)
46    }
47
48    /// Read a constant value.
49    #[inline]
50    pub fn constant(&self, hash: &Hash) -> Option<&ConstValue> {
51        self.constants.get(hash)
52    }
53
54    /// Read a constant constructor.
55    #[inline]
56    pub(crate) fn construct(&self, hash: &Hash) -> Option<&ConstConstructImpl> {
57        self.construct.get(hash)
58    }
59}
60
61impl fmt::Debug for RuntimeContext {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        write!(f, "RuntimeContext")
64    }
65}
66
67#[cfg(test)]
68static_assertions::assert_impl_all!(RuntimeContext: Send, Sync);