Skip to main content

mirascript_vm/
context.rs

1use indexmap::IndexMap;
2
3use crate::{MiraAny, MiraNativeFn};
4
5/// Globals visible to a MiraScript execution.
6#[derive(Clone)]
7pub struct MiraContext {
8    values: IndexMap<String, MiraAny>,
9}
10
11impl MiraContext {
12    /// Create a context populated with the MiraScript standard library.
13    pub fn new() -> Self {
14        let mut context = Self {
15            values: IndexMap::new(),
16        };
17        crate::standard_library::install(&mut context);
18        context
19    }
20
21    /// Create a context without standard-library globals.
22    pub fn empty() -> Self {
23        Self {
24            values: IndexMap::new(),
25        }
26    }
27
28    /// Insert or replace a global value, returning the previous value.
29    ///
30    /// # Examples
31    ///
32    /// ```
33    /// use mirascript_vm::{MiraAny, MiraContext};
34    ///
35    /// let mut context = MiraContext::empty();
36    /// assert_eq!(context.insert("answer", 42), None);
37    /// assert_eq!(context.get("answer"), Some(MiraAny::Number(42.0)));
38    /// ```
39    pub fn insert(
40        &mut self,
41        name: impl Into<String>,
42        value: impl Into<MiraAny>,
43    ) -> Option<MiraAny> {
44        self.values.insert(name.into(), value.into())
45    }
46
47    /// Insert or replace a named native function.
48    pub fn insert_fn(&mut self, name: impl Into<String>, function: impl Into<MiraNativeFn>) {
49        self.insert(
50            name,
51            MiraAny::Function(crate::MiraFunction::Native(function.into())),
52        );
53    }
54
55    /// Clone a global value by name.
56    pub fn get(&self, name: &str) -> Option<MiraAny> {
57        self.get_ref(name).cloned()
58    }
59
60    pub(crate) fn get_ref(&self, name: &str) -> Option<&MiraAny> {
61        self.values.get(name)
62    }
63
64    /// Return whether a global name is defined.
65    pub fn contains(&self, name: &str) -> bool {
66        self.values.contains_key(name)
67    }
68
69    /// Iterate over global names in insertion order.
70    pub fn keys(&self) -> impl Iterator<Item = &str> {
71        self.values.keys().map(String::as_str)
72    }
73}
74
75impl Default for MiraContext {
76    fn default() -> Self {
77        Self::new()
78    }
79}