Skip to main content

mirascript_vm/value/arena/
mod.rs

1mod id;
2mod key;
3
4use std::{any::Any, fmt, marker::PhantomData, ops::Deref, rc::Rc};
5
6use crate::{MiraError, Result, Runtime, RuntimeErrorKind};
7
8use super::{MiraArray, MiraFunction, MiraModule, MiraRecord, MiraValue, MiraValueKind};
9
10use id::ArenaId;
11use key::ArenaKey;
12
13#[derive(Debug)]
14struct Arena<T> {
15    values: Vec<T>,
16}
17
18impl<T> Arena<T> {
19    fn new() -> Self {
20        Self { values: Vec::new() }
21    }
22
23    fn insert(&mut self, arena_id: ArenaId, category: &'static str, value: T) -> Result<ArenaKey> {
24        let key = ArenaKey::new(arena_id, self.values.len(), category)?;
25        self.values.push(value);
26        Ok(key)
27    }
28
29    fn get(&self, arena_id: ArenaId, category: &'static str, key: ArenaKey) -> Result<&T> {
30        if key.arena_id() != arena_id {
31            return Err(MiraError::runtime(RuntimeErrorKind::ForeignHandle));
32        }
33        self.values
34            .get(key.index())
35            .ok_or_else(|| MiraError::runtime(RuntimeErrorKind::InvalidHandle { category }))
36    }
37
38    fn get_mut(
39        &mut self,
40        arena_id: ArenaId,
41        category: &'static str,
42        key: ArenaKey,
43    ) -> Result<&mut T> {
44        if key.arena_id() != arena_id {
45            return Err(MiraError::runtime(RuntimeErrorKind::ForeignHandle));
46        }
47        self.values
48            .get_mut(key.index())
49            .ok_or_else(|| MiraError::runtime(RuntimeErrorKind::InvalidHandle { category }))
50    }
51}
52
53/// A compact, runtime-checked handle to an arena-managed value.
54pub struct MiraHandle<T: Any + ?Sized> {
55    key: ArenaKey,
56    marker: PhantomData<&'static T>,
57}
58
59impl<T: Any + ?Sized> Copy for MiraHandle<T> {}
60
61impl<T: Any + ?Sized> Clone for MiraHandle<T> {
62    fn clone(&self) -> Self {
63        *self
64    }
65}
66
67impl<T: Any + ?Sized> fmt::Debug for MiraHandle<T> {
68    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
69        formatter
70            .debug_struct("MiraHandle")
71            .field("arena", &self.key.arena_id().get())
72            .field("slot", &self.key.index())
73            .finish()
74    }
75}
76
77impl<T: Any + ?Sized> PartialEq for MiraHandle<T> {
78    fn eq(&self, other: &Self) -> bool {
79        self.key == other.key
80    }
81}
82
83impl<T: Any + ?Sized> Eq for MiraHandle<T> {}
84
85impl<T: Any + ?Sized> std::hash::Hash for MiraHandle<T> {
86    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
87        self.key.hash(state);
88    }
89}
90
91impl<T: Any + ?Sized> MiraHandle<T> {
92    fn new(key: ArenaKey) -> Self {
93        Self {
94            key,
95            marker: PhantomData,
96        }
97    }
98
99    pub(crate) fn payload(self) -> [u8; 6] {
100        self.key.payload()
101    }
102
103    pub(crate) fn from_payload(payload: [u8; 6]) -> Self {
104        Self::new(ArenaKey::from_payload(payload))
105    }
106}
107
108macro_rules! impl_handle_cast {
109    ($trait:path, $erase:ident) => {
110        impl<T: $trait + ?Sized> MiraHandle<T> {
111            /// Erase the concrete Rust type while preserving its MiraScript category.
112            pub fn $erase(self) -> MiraHandle<dyn $trait> {
113                MiraHandle::new(self.key)
114            }
115        }
116
117        impl MiraHandle<dyn $trait> {
118            /// Reinterpret an erased handle as a concrete typed handle.
119            ///
120            /// The subsequent Runtime lookup still validates the concrete type,
121            /// so a wrong generated cast returns an error rather than dereferencing
122            /// an invalid pointer.
123            #[doc(hidden)]
124            pub unsafe fn upcast<T: $trait>(self) -> MiraHandle<T> {
125                MiraHandle::new(self.key)
126            }
127        }
128    };
129}
130
131impl_handle_cast!(MiraArray, erase_array);
132impl_handle_cast!(MiraRecord, erase_record);
133impl_handle_cast!(MiraFunction, erase_function);
134impl_handle_cast!(MiraModule, erase_module);
135
136/// An owned value waiting to be inserted into a Runtime arena.
137pub enum MiraManageable {
138    /// A value whose payload is already inline or already belongs to this Runtime.
139    Value(MiraValue),
140    /// An owned string.
141    String(String),
142    /// An owned array implementation.
143    Array(Box<dyn MiraArray>),
144    /// An owned record implementation.
145    Record(Box<dyn MiraRecord>),
146    /// An owned callable implementation.
147    Function(Rc<dyn MiraFunction>),
148    /// An owned module implementation.
149    Module(Box<dyn MiraModule>),
150}
151
152impl From<MiraValue> for MiraManageable {
153    fn from(value: MiraValue) -> Self {
154        Self::Value(value)
155    }
156}
157
158impl From<String> for MiraManageable {
159    fn from(value: String) -> Self {
160        Self::String(value)
161    }
162}
163
164impl From<&str> for MiraManageable {
165    fn from(value: &str) -> Self {
166        Self::String(value.to_owned())
167    }
168}
169
170impl MiraManageable {
171    /// Wrap an array implementation for insertion into a Runtime.
172    pub fn from_array(value: impl MiraArray) -> Self {
173        Self::Array(Box::new(value))
174    }
175
176    /// Wrap a record implementation for insertion into a Runtime.
177    pub fn from_record(value: impl MiraRecord) -> Self {
178        Self::Record(Box::new(value))
179    }
180
181    /// Wrap a function implementation for insertion into a Runtime.
182    pub fn from_function(value: impl MiraFunction) -> Self {
183        Self::Function(Rc::new(value))
184    }
185
186    /// Wrap a module implementation for insertion into a Runtime.
187    pub fn from_module(value: impl MiraModule) -> Self {
188        Self::Module(Box::new(value))
189    }
190
191    /// Build a simple named module from already materialized Runtime values.
192    pub fn map_module(
193        name: impl Into<String>,
194        values: indexmap::IndexMap<String, MiraValue>,
195    ) -> Self {
196        crate::value::types::map_module(name, values)
197    }
198}
199
200pub(crate) struct MiraArena {
201    id: ArenaId,
202    strings: Arena<String>,
203    arrays: Arena<Box<dyn MiraArray>>,
204    records: Arena<Box<dyn MiraRecord>>,
205    functions: Arena<Rc<dyn MiraFunction>>,
206    modules: Arena<Box<dyn MiraModule>>,
207}
208
209impl MiraArena {
210    pub(crate) fn new() -> Self {
211        Self {
212            id: ArenaId::next(),
213            strings: Arena::new(),
214            arrays: Arena::new(),
215            records: Arena::new(),
216            functions: Arena::new(),
217            modules: Arena::new(),
218        }
219    }
220}
221
222impl Runtime {
223    /// Insert an owned value into this Runtime when necessary.
224    pub fn insert(&mut self, value: impl Into<MiraManageable>) -> Result<MiraValue> {
225        match value.into() {
226            MiraManageable::Value(value) => {
227                self.validate_value(&value)?;
228                Ok(value)
229            }
230            MiraManageable::String(value) => {
231                Ok(MiraValue::from_string_handle(self.insert_string(value)?))
232            }
233            MiraManageable::Array(value) => {
234                let key = self.arena.arrays.insert(self.arena.id, "array", value)?;
235                Ok(MiraValue::from_array_handle(MiraHandle::new(key)))
236            }
237            MiraManageable::Record(value) => {
238                let key = self.arena.records.insert(self.arena.id, "record", value)?;
239                Ok(MiraValue::from_record_handle(MiraHandle::new(key)))
240            }
241            MiraManageable::Function(value) => {
242                let key = self
243                    .arena
244                    .functions
245                    .insert(self.arena.id, "function", value)?;
246                Ok(MiraValue::from_function_handle(MiraHandle::new(key)))
247            }
248            MiraManageable::Module(value) => {
249                let key = self.arena.modules.insert(self.arena.id, "module", value)?;
250                Ok(MiraValue::from_module_handle(MiraHandle::new(key)))
251            }
252        }
253    }
254
255    /// Insert an owned string and return its typed handle.
256    pub fn insert_string(&mut self, value: impl Into<String>) -> Result<MiraHandle<String>> {
257        let key = self
258            .arena
259            .strings
260            .insert(self.arena.id, "string", value.into())?;
261        Ok(MiraHandle::new(key))
262    }
263
264    /// Read a string handle owned by this Runtime.
265    pub fn get_string(&self, handle: MiraHandle<String>) -> Result<&str> {
266        self.arena
267            .strings
268            .get(self.arena.id, "string", handle.key)
269            .map(Deref::deref)
270    }
271
272    /// Mutably read a string handle owned by this Runtime.
273    pub fn get_string_mut(&mut self, handle: MiraHandle<String>) -> Result<&mut String> {
274        self.arena
275            .strings
276            .get_mut(self.arena.id, "string", handle.key)
277    }
278
279    /// Insert an array and return a concrete typed handle.
280    pub fn insert_array<T: MiraArray>(&mut self, value: T) -> Result<MiraHandle<T>> {
281        let key = self
282            .arena
283            .arrays
284            .insert(self.arena.id, "array", Box::new(value))?;
285        Ok(MiraHandle::new(key))
286    }
287
288    /// Insert a record and return a concrete typed handle.
289    pub fn insert_record<T: MiraRecord>(&mut self, value: T) -> Result<MiraHandle<T>> {
290        let key = self
291            .arena
292            .records
293            .insert(self.arena.id, "record", Box::new(value))?;
294        Ok(MiraHandle::new(key))
295    }
296
297    /// Insert a function and return a concrete typed handle.
298    pub fn insert_function<T: MiraFunction>(&mut self, value: T) -> Result<MiraHandle<T>> {
299        let key = self
300            .arena
301            .functions
302            .insert(self.arena.id, "function", Rc::new(value))?;
303        Ok(MiraHandle::new(key))
304    }
305
306    /// Insert a module and return a concrete typed handle.
307    pub fn insert_module<T: MiraModule>(&mut self, value: T) -> Result<MiraHandle<T>> {
308        let key = self
309            .arena
310            .modules
311            .insert(self.arena.id, "module", Box::new(value))?;
312        Ok(MiraHandle::new(key))
313    }
314
315    pub(crate) fn get_array_dyn(
316        &self,
317        handle: MiraHandle<dyn MiraArray>,
318    ) -> Result<&dyn MiraArray> {
319        self.arena
320            .arrays
321            .get(self.arena.id, "array", handle.key)
322            .map(|value| value.as_ref())
323    }
324
325    pub(crate) fn get_record_dyn(
326        &self,
327        handle: MiraHandle<dyn MiraRecord>,
328    ) -> Result<&dyn MiraRecord> {
329        self.arena
330            .records
331            .get(self.arena.id, "record", handle.key)
332            .map(|value| value.as_ref())
333    }
334
335    pub(crate) fn get_function_dyn(
336        &self,
337        handle: MiraHandle<dyn MiraFunction>,
338    ) -> Result<Rc<dyn MiraFunction>> {
339        self.arena
340            .functions
341            .get(self.arena.id, "function", handle.key)
342            .map(Rc::clone)
343    }
344
345    pub(crate) fn get_module_dyn(
346        &self,
347        handle: MiraHandle<dyn MiraModule>,
348    ) -> Result<&dyn MiraModule> {
349        self.arena
350            .modules
351            .get(self.arena.id, "module", handle.key)
352            .map(|value| value.as_ref())
353    }
354
355    /// Read the concrete target represented by a typed array handle.
356    pub fn get_array<T: MiraArray>(&self, handle: MiraHandle<T>) -> Result<&T> {
357        let value = self.arena.arrays.get(self.arena.id, "array", handle.key)?;
358        let value: &dyn Any = value.resolve(self)?.unwrap_or(value.as_ref());
359        value.downcast_ref::<T>().ok_or_else(|| {
360            MiraError::runtime(RuntimeErrorKind::HandleTypeMismatch { category: "array" })
361        })
362    }
363
364    /// Mutably read the concrete object stored directly behind an array handle.
365    pub fn get_array_mut<T: MiraArray>(&mut self, handle: MiraHandle<T>) -> Result<&mut T> {
366        let value = self
367            .arena
368            .arrays
369            .get_mut(self.arena.id, "array", handle.key)?;
370        let value: &mut dyn Any = value.as_mut();
371        value.downcast_mut::<T>().ok_or_else(|| {
372            MiraError::runtime(RuntimeErrorKind::HandleTypeMismatch { category: "array" })
373        })
374    }
375
376    /// Read the concrete target represented by a typed record handle.
377    pub fn get_record<T: MiraRecord>(&self, handle: MiraHandle<T>) -> Result<&T> {
378        let value = self
379            .arena
380            .records
381            .get(self.arena.id, "record", handle.key)?;
382        let value: &dyn Any = value.resolve(self)?.unwrap_or(value.as_ref());
383        value.downcast_ref::<T>().ok_or_else(|| {
384            MiraError::runtime(RuntimeErrorKind::HandleTypeMismatch { category: "record" })
385        })
386    }
387
388    /// Mutably read the concrete object stored directly behind a record handle.
389    pub fn get_record_mut<T: MiraRecord>(&mut self, handle: MiraHandle<T>) -> Result<&mut T> {
390        let value = self
391            .arena
392            .records
393            .get_mut(self.arena.id, "record", handle.key)?;
394        let value: &mut dyn Any = value.as_mut();
395        value.downcast_mut::<T>().ok_or_else(|| {
396            MiraError::runtime(RuntimeErrorKind::HandleTypeMismatch { category: "record" })
397        })
398    }
399
400    /// Read the concrete function stored behind a typed handle.
401    pub fn get_function<T: MiraFunction>(&self, handle: MiraHandle<T>) -> Result<&T> {
402        let value = self
403            .arena
404            .functions
405            .get(self.arena.id, "function", handle.key)?;
406        let value: &dyn Any = value.as_ref();
407        value.downcast_ref::<T>().ok_or_else(|| {
408            MiraError::runtime(RuntimeErrorKind::HandleTypeMismatch {
409                category: "function",
410            })
411        })
412    }
413
414    /// Read the concrete module stored behind a typed handle.
415    pub fn get_module<T: MiraModule>(&self, handle: MiraHandle<T>) -> Result<&T> {
416        let value = self
417            .arena
418            .modules
419            .get(self.arena.id, "module", handle.key)?;
420        let value: &dyn Any = value.as_ref();
421        value.downcast_ref::<T>().ok_or_else(|| {
422            MiraError::runtime(RuntimeErrorKind::HandleTypeMismatch { category: "module" })
423        })
424    }
425
426    /// Mutably read the concrete module stored behind a typed handle.
427    pub fn get_module_mut<T: MiraModule>(&mut self, handle: MiraHandle<T>) -> Result<&mut T> {
428        let value = self
429            .arena
430            .modules
431            .get_mut(self.arena.id, "module", handle.key)?;
432        let value: &mut dyn Any = value.as_mut();
433        value.downcast_mut::<T>().ok_or_else(|| {
434            MiraError::runtime(RuntimeErrorKind::HandleTypeMismatch { category: "module" })
435        })
436    }
437
438    pub(crate) fn validate_value(&self, value: &MiraValue) -> Result<()> {
439        match value.kind() {
440            MiraValueKind::String(handle) => self.get_string(handle).map(|_| ()),
441            MiraValueKind::Array(handle) => self.get_array_dyn(handle).map(|_| ()),
442            MiraValueKind::Record(handle) => self.get_record_dyn(handle).map(|_| ()),
443            MiraValueKind::Function(handle) => self.get_function_dyn(handle).map(|_| ()),
444            MiraValueKind::Module(handle) => self.get_module_dyn(handle).map(|_| ()),
445            MiraValueKind::Extern(_) => Err(MiraError::runtime(RuntimeErrorKind::InvalidHandle {
446                category: "extern",
447            })),
448            MiraValueKind::Nil
449            | MiraValueKind::Boolean(_)
450            | MiraValueKind::Number(_)
451            | MiraValueKind::StaticStr(_) => Ok(()),
452        }
453    }
454}
455