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