Skip to main content

rune/runtime/
runtime_context.rs

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