Skip to main content

mirascript_vm/value/arena/
mod.rs

1mod handle;
2mod id;
3mod key;
4mod manageable;
5mod typed_arena;
6
7use std::{any::Any, ops::Deref, rc::Rc};
8
9use crate::{MiraError, Result, Runtime, RuntimeErrorKind};
10
11use super::{MiraArray, MiraFunction, MiraModule, MiraRecord, MiraValue, MiraValueKind, Payload};
12
13pub use handle::MiraHandle;
14use id::ArenaId;
15use key::ArenaKey;
16pub use manageable::MiraManageable;
17use typed_arena::{Arena, CAT_ARRAY, CAT_FUNCTION, CAT_MODULE, CAT_RECORD, CAT_STRING};
18
19pub(crate) struct MiraArena {
20    id: ArenaId,
21    strings: Arena<CAT_STRING, String>,
22    arrays: Arena<CAT_ARRAY, Box<dyn MiraArray>>,
23    records: Arena<CAT_RECORD, Box<dyn MiraRecord>>,
24    functions: Arena<CAT_FUNCTION, Rc<dyn MiraFunction>>,
25    modules: Arena<CAT_MODULE, Box<dyn MiraModule>>,
26}
27
28impl MiraArena {
29    pub(crate) fn new() -> Self {
30        Self {
31            id: ArenaId::next(),
32            strings: Arena::new(),
33            arrays: Arena::new(),
34            records: Arena::new(),
35            functions: Arena::new(),
36            modules: Arena::new(),
37        }
38    }
39}
40
41impl Runtime {
42    /// Insert an owned value into this Runtime when necessary.
43    pub fn insert(&mut self, value: impl Into<MiraManageable>) -> Result<MiraValue> {
44        match value.into() {
45            MiraManageable::Value(value) => {
46                self.validate_value(&value)?;
47                Ok(value)
48            }
49            MiraManageable::String(value) => {
50                let key = self.arena.strings.insert(self.arena.id, value)?;
51                Ok(MiraValue::string(MiraHandle::new(key)))
52            }
53            MiraManageable::Array(value) => {
54                let key = self.arena.arrays.insert(self.arena.id, value)?;
55                Ok(MiraValue::array(MiraHandle::<dyn MiraArray>::new(key)))
56            }
57            MiraManageable::Record(value) => {
58                let key = self.arena.records.insert(self.arena.id, value)?;
59                Ok(MiraValue::record(MiraHandle::<dyn MiraRecord>::new(key)))
60            }
61            MiraManageable::Function(value) => {
62                let key = self.arena.functions.insert(self.arena.id, value)?;
63                Ok(MiraValue::function(MiraHandle::<dyn MiraFunction>::new(
64                    key,
65                )))
66            }
67            MiraManageable::Module(value) => {
68                let key = self.arena.modules.insert(self.arena.id, value)?;
69                Ok(MiraValue::module(MiraHandle::<dyn MiraModule>::new(key)))
70            }
71        }
72    }
73
74    pub(crate) fn validate_value(&self, value: &MiraValue) -> Result<()> {
75        match value.kind() {
76            MiraValueKind::String(handle) => self.get_string(handle).map(|_| ()),
77            MiraValueKind::Array(handle) => self.get_array_dyn(handle).map(|_| ()),
78            MiraValueKind::Record(handle) => self.get_record_dyn(handle).map(|_| ()),
79            MiraValueKind::Function(handle) => self.get_function_dyn(handle).map(|_| ()),
80            MiraValueKind::Module(handle) => self.get_module_dyn(handle).map(|_| ()),
81            MiraValueKind::Extern(_) => Err(MiraError::runtime(RuntimeErrorKind::InvalidHandle {
82                category: "extern",
83            })),
84            MiraValueKind::Nil
85            | MiraValueKind::Boolean(_)
86            | MiraValueKind::Number(_)
87            | MiraValueKind::StaticStr(_) => Ok(()),
88        }
89    }
90}
91
92/// Functions for working with string handles.
93impl Runtime {
94    /// Insert an owned string and return its typed handle.
95    pub fn insert_string(&mut self, value: impl Into<String>) -> Result<MiraHandle<String>> {
96        let key = self.arena.strings.insert(self.arena.id, value.into())?;
97        Ok(MiraHandle::new(key))
98    }
99
100    /// Read a string handle owned by this Runtime.
101    pub fn get_string(&self, handle: MiraHandle<String>) -> Result<&str> {
102        self.arena
103            .strings
104            .get(self.arena.id, handle.key)
105            .map(Deref::deref)
106    }
107
108    /// Mutably read a string handle owned by this Runtime.
109    pub fn get_string_mut(&mut self, handle: MiraHandle<String>) -> Result<&mut String> {
110        self.arena.strings.get_mut(self.arena.id, handle.key)
111    }
112
113    /// Take a string handle owned by this Runtime, consuming the handle.
114    pub fn take_string(&mut self, handle: MiraHandle<String>) -> Result<String> {
115        self.arena.strings.take(self.arena.id, handle.key)
116    }
117}
118
119/// Functions for working with function handles.
120impl Runtime {
121    /// Insert a function and return a concrete typed handle.
122    pub fn insert_function<T: MiraFunction>(&mut self, value: T) -> Result<MiraHandle<T>> {
123        let key = self.arena.functions.insert(self.arena.id, Rc::new(value))?;
124        Ok(MiraHandle::new(key))
125    }
126
127    pub(crate) fn get_function_dyn(
128        &self,
129        handle: MiraHandle<dyn MiraFunction>,
130    ) -> Result<Rc<dyn MiraFunction>> {
131        self.arena
132            .functions
133            .get(self.arena.id, handle.key)
134            .map(Rc::clone)
135    }
136
137    /// Read the concrete function stored behind a typed handle.
138    pub fn get_function<T: MiraFunction>(&self, handle: MiraHandle<T>) -> Result<&T> {
139        let value = self.arena.functions.get(self.arena.id, handle.key)?;
140        let value: &dyn Any = value.as_ref();
141        value.downcast_ref::<T>().ok_or_else(|| {
142            MiraError::runtime(RuntimeErrorKind::HandleTypeMismatch {
143                category: "function",
144            })
145        })
146    }
147
148    /// Take the concrete function stored behind a typed handle, consuming the handle.
149    pub fn take_function<T: MiraFunction>(&mut self, handle: MiraHandle<T>) -> Result<Rc<T>> {
150        let value = self.arena.functions.take(self.arena.id, handle.key)?;
151        let value: Rc<dyn Any> = value;
152        value.downcast::<T>().map_err(|_| {
153            MiraError::runtime(RuntimeErrorKind::HandleTypeMismatch {
154                category: "function",
155            })
156        })
157    }
158}
159
160macro_rules! impl_typed_functions {
161    ($field:ident, $name:ident, $trait:ident) => { paste::paste! {
162        #[doc = concat!("Functions for working with ", stringify!($name), " handles.")]
163        impl Runtime {
164            #[doc = concat!("Insert a ", stringify!($name), " and return a concrete typed handle.")]
165            pub fn [<insert_ $name>]<T: $trait>(&mut self, value: T) -> Result<MiraHandle<T>> {
166                let key = self.arena.$field.insert(self.arena.id, Box::new(value))?;
167                Ok(MiraHandle::new(key))
168            }
169
170            pub(crate) fn [<get_ $name _dyn>](
171                &self,
172                handle: MiraHandle<dyn $trait>,
173            ) -> Result<&dyn $trait> {
174                self.arena
175                    .$field
176                    .get(self.arena.id, handle.key)
177                    .map(|value| value.as_ref())
178            }
179
180            #[doc = concat!("Read the concrete target represented by a typed ", stringify!($name), " handle.")]
181            pub fn [<get_ $name>]<T: $trait>(&self, handle: MiraHandle<T>) -> Result<&T> {
182                let value = self.arena.$field.get(self.arena.id, handle.key)?;
183                let value: &dyn Any = value.resolve(self)?.unwrap_or(value.as_ref());
184                value.downcast_ref::<T>().ok_or_else(|| {
185                    MiraError::runtime(RuntimeErrorKind::HandleTypeMismatch { category: stringify!($name) })
186                })
187            }
188
189            #[doc = concat!("Mutably read the concrete object stored directly behind a ", stringify!($name), " handle.")]
190            pub fn [<get_ $name _mut>]<T: $trait>(&mut self, handle: MiraHandle<T>) -> Result<&mut T> {
191                let value = self.arena.$field.get_mut(self.arena.id, handle.key)?;
192                let value: &mut dyn Any = value.as_mut();
193                value.downcast_mut::<T>().ok_or_else(|| {
194                    MiraError::runtime(RuntimeErrorKind::HandleTypeMismatch { category: stringify!($name) })
195                })
196            }
197
198            #[doc = concat!("Take the concrete object stored directly behind a ", stringify!($name), " handle, consuming the handle.")]
199            pub fn [<take_ $name>]<T: $trait>(&mut self, handle: MiraHandle<T>) -> Result<T> {
200                let value = self.arena.$field.take(self.arena.id, handle.key)?;
201                let value: Box<dyn Any> = value;
202                value.downcast::<T>().map(|boxed| *boxed).map_err(|_| {
203                    MiraError::runtime(RuntimeErrorKind::HandleTypeMismatch { category: stringify!($name) })
204                })
205            }
206        }
207    } };
208}
209
210impl_typed_functions!(arrays, array, MiraArray);
211impl_typed_functions!(records, record, MiraRecord);
212impl_typed_functions!(modules, module, MiraModule);