Skip to main content

mirascript_vm/interpreter/
globals.rs

1use std::{cell::LazyCell, collections::HashMap, ops::Deref};
2
3use indexmap::IndexMap;
4
5use crate::{MiraManageable, MiraNativeFn};
6
7use super::*;
8
9const GLOBALS_VEC_THRESHOLD: usize = 16;
10
11enum GlobalData {
12    Vec(Vec<(String, MiraAny)>),
13    Map(HashMap<String, MiraAny>),
14}
15
16fn read_global(value: Option<MiraAny>) -> Option<MiraValue> {
17    match value {
18        Some(value) if !value.is_uninitialized() => Some(value.unwrap()),
19        _ => None,
20    }
21}
22
23impl GlobalData {
24    fn get(&self, name: &str) -> Option<MiraValue> {
25        let value = match self {
26            GlobalData::Vec(vec) => vec.iter().find_map(|(existing_name, existing_value)| {
27                if existing_name == name {
28                    Some(existing_value)
29                } else {
30                    None
31                }
32            }),
33            GlobalData::Map(map) => map.get(name),
34        };
35        read_global(value.cloned())
36    }
37
38    fn insert(&mut self, name: String, value: MiraValue) -> Option<MiraValue> {
39        match self {
40            GlobalData::Vec(vec) => {
41                if let Some((_, existing_value)) = vec
42                    .iter_mut()
43                    .find(|(existing_name, _)| existing_name == &name)
44                {
45                    return read_global(Some(std::mem::replace(existing_value, value.into())));
46                }
47                vec.push((name, value.into()));
48                if vec.len() > GLOBALS_VEC_THRESHOLD {
49                    let map = vec.drain(..).collect::<HashMap<_, _>>();
50                    *self = GlobalData::Map(map);
51                }
52                None
53            }
54            GlobalData::Map(map) => read_global(map.insert(name, value.into())),
55        }
56    }
57
58    fn contains_key(&self, name: &str) -> bool {
59        match self {
60            GlobalData::Vec(vec) => vec.iter().any(|(existing_name, _)| existing_name == name),
61            GlobalData::Map(map) => map.contains_key(name),
62        }
63    }
64
65    fn len(&self) -> usize {
66        match self {
67            GlobalData::Vec(vec) => vec.len(),
68            GlobalData::Map(map) => map.len(),
69        }
70    }
71}
72
73pub(crate) struct Globals {
74    std: IndexMap<&'static str, MiraAny>,
75    context: GlobalData,
76}
77
78impl Globals {
79    pub(super) fn new() -> Self {
80        Self {
81            std: IndexMap::new(),
82            context: GlobalData::Vec(Vec::new()),
83        }
84    }
85
86    fn insert_std(&mut self, name: &'static str, value: MiraValue) -> usize {
87        debug_assert!(
88            !self.std.contains_key(name),
89            "standard-library global name collision: {name}"
90        );
91        debug_assert_eq!(
92            self.context.len(),
93            0,
94            "standard-library globals must be inserted before any context globals"
95        );
96        debug_assert!(
97            !value.is_uninitialized(),
98            "standard-library globals must be initialized"
99        );
100
101        self.std.insert(name, value.into());
102        self.std.len() - 1
103    }
104
105    fn insert(&mut self, name: String, value: MiraValue) -> Option<MiraValue> {
106        if let Some(std_slot) = self.std.get_mut(name.as_str()) {
107            return read_global(Some(std::mem::replace(std_slot, value.into())));
108        }
109        self.context.insert(name, value)
110    }
111
112    pub fn get(&self, name: &str) -> Option<MiraValue> {
113        self.context
114            .get(name)
115            .or_else(|| read_global(self.std.get(name).cloned()))
116    }
117
118    pub fn get_hint(&self, name: &str, index: Option<usize>) -> Option<MiraValue> {
119        if let Some(index) = index
120            && let Some((std_name, value)) = self.std.get_index(index)
121        {
122            debug_assert_eq!(
123                *std_name, name,
124                "standard-library global name collision: expected {std_name}, got {name}"
125            );
126            read_global(Some(*value))
127        } else {
128            self.get(name)
129        }
130    }
131
132    pub fn contains_key(&self, name: &str) -> bool {
133        self.std.contains_key(name) || self.context.contains_key(name)
134    }
135
136    fn keys(&self) -> impl Iterator<Item = &str> {
137        let mut keys = self.std.keys().map(Deref::deref).collect::<Vec<_>>();
138        match &self.context {
139            GlobalData::Vec(vec) => keys.extend(vec.iter().map(|(k, _)| k.as_str())),
140            GlobalData::Map(map) => keys.extend(map.keys().map(String::as_str)),
141        }
142        keys.into_iter()
143    }
144}
145
146impl Runtime {
147    /// Insert or replace a global after converting it into a Runtime value.
148    pub fn insert_global(
149        &mut self,
150        name: impl Into<String>,
151        value: impl Into<MiraManageable>,
152    ) -> Result<Option<MiraValue>> {
153        let value = self.insert(value)?;
154        Ok(self.globals.insert(name.into(), value))
155    }
156
157    /// Insert a named native function into the global namespace.
158    pub fn insert_fn(
159        &mut self,
160        name: impl Into<String>,
161        function: impl Into<MiraNativeFn>,
162    ) -> Result<Option<MiraValue>> {
163        let name = name.into();
164        let function = function.into().with_name(name.clone());
165        let handle = self.insert_function(function)?;
166        Ok(self.globals.insert(name, MiraValue::function(handle)))
167    }
168
169    /// Clone a global value by name.
170    pub fn get_global(&self, name: &str) -> Option<MiraValue> {
171        self.globals.get(name)
172    }
173
174    /// Return whether a global name is defined.
175    pub fn contains_global(&self, name: &str) -> bool {
176        self.globals.contains_key(name)
177    }
178
179    /// Remove a global value by name, returning the previous value if it existed.
180    /// You shall call `take_*` to remove the value from the Runtime's arena if you want to reclaim its memory.
181    pub fn remove_global(&mut self, name: &str) -> Option<MiraValue> {
182        if !self.globals.contains_key(name) {
183            None
184        } else {
185            self.globals
186                .insert(name.to_string(), MiraValue::UNINITIALIZED)
187        }
188    }
189
190    /// Iterate over global names in insertion order.
191    pub fn global_names(&self) -> impl Iterator<Item = &str> {
192        self.globals.keys()
193    }
194
195    pub(crate) fn insert_std(
196        &mut self,
197        name: &'static str,
198        value: impl Into<MiraManageable>,
199    ) -> usize {
200        let value = self
201            .insert(value)
202            .expect("standard-library function allocation must fit in a fresh Runtime arena");
203        self.globals.insert_std(name, value)
204    }
205}
206
207thread_local! {
208    static RUNTIME: LazyCell<IndexMap<&'static str, ()>> = LazyCell::new(||{
209        let runtime = Runtime::new();
210        let std = runtime.globals.std;
211        std.into_keys().map(|name| (name, ())).collect()
212    });
213}
214
215pub(crate) fn std_slot(name: &str) -> Option<usize> {
216    RUNTIME.with(|l| l.get_index_of(name))
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222
223    #[test]
224    fn std_slot_returns_none_for_nonexistent_name() {
225        let index = std_slot("nonexistent");
226        assert!(index.is_none());
227    }
228
229    #[test]
230    fn add_global() {
231        let mut runtime = Runtime::new();
232
233        assert!(!runtime.contains_global("foo"));
234
235        // Insert a global and verify it can be retrieved.
236        runtime.insert_global("foo", 42).unwrap();
237        assert_eq!(
238            runtime.get_global("foo").unwrap().as_number_unchecked(),
239            42.0
240        );
241
242        // Remove the global and verify it is no longer present.
243        let removed = runtime.remove_global("foo");
244        assert_eq!(removed.unwrap().as_number_unchecked(), 42.0);
245        assert!(runtime.get_global("foo").is_none());
246
247        // Insert a new global with the same name and verify it can be retrieved.
248        runtime.insert_global("foo", "Hello").unwrap();
249        assert_eq!(
250            runtime.get_global("foo").unwrap().as_str(&runtime).unwrap(),
251            Some("Hello")
252        );
253    }
254
255    #[test]
256    fn add_std_global() {
257        let mut runtime = Runtime::new();
258
259        assert!(runtime.contains_global("sin"));
260
261        // Insert a global and verify it can be retrieved.
262        runtime.insert_global("sin", 42).unwrap();
263        assert_eq!(
264            runtime.get_global("sin").unwrap().as_number_unchecked(),
265            42.0
266        );
267
268        // Remove the global and verify it is no longer present.
269        let removed = runtime.remove_global("sin");
270        assert_eq!(removed.unwrap().as_number_unchecked(), 42.0);
271        assert!(runtime.get_global("sin").is_none());
272
273        // Insert a new global with the same name and verify it can be retrieved.
274        runtime.insert_global("sin", "Hello").unwrap();
275        assert_eq!(
276            runtime.get_global("sin").unwrap().as_str(&runtime).unwrap(),
277            Some("Hello")
278        );
279    }
280
281    #[test]
282    fn remove_std() {
283        let mut runtime = Runtime::new();
284
285        assert!(runtime.contains_global("sin"));
286
287        // Remove the global and verify it is no longer present.
288        let removed = runtime.remove_global("sin");
289        assert!(removed.unwrap().is_function());
290        assert!(runtime.get_global("sin").is_none());
291
292        // Re-add the global and verify it can be retrieved.
293        runtime.insert_global("sin", removed.unwrap()).unwrap();
294        assert!(runtime.get_global("sin").unwrap().is_function());
295
296        assert_eq!(runtime.eval_unchecked("sin(0)").as_number_unchecked(), 0.0);
297    }
298
299    #[test]
300    fn remove_nonexistent() {
301        let mut runtime = Runtime::new();
302
303        assert!(!runtime.contains_global("nonexistent"));
304
305        // Remove the global and verify it is no longer present.
306        let removed = runtime.remove_global("nonexistent");
307        assert!(removed.is_none());
308    }
309
310    #[test]
311    fn iter_global_names() {
312        let mut runtime = Runtime::new();
313
314        let names: Vec<_> = runtime.global_names().collect();
315        assert!(names.contains(&"sin"));
316        assert!(names.contains(&"cos"));
317
318        runtime.insert_global("foo", 42).unwrap();
319        runtime.insert_global("bar", "Hello").unwrap();
320
321        let names: Vec<_> = runtime.global_names().collect();
322        assert!(names.contains(&"sin"));
323        assert!(names.contains(&"cos"));
324        assert!(names.contains(&"foo"));
325        assert!(names.contains(&"bar"));
326    }
327}